开发者

Django - displaying a table that spans 3 models

开发者 https://www.devze.com 2023-03-21 09:47 出处:网络
I have 3 related fields, and I\'m trying to figure out a good way to build a table that displays all three.

I have 3 related fields, and I'm trying to figure out a good way to build a table that displays all three. I have Employees, CertificateTypes and Certificates, with Certificates linking Employee and CertificateType. CertificateTypes are basically types of training an Employee can receive and Certificates are the training an Employee has received in a CertificateType.

Eg: (a parallel example): a student can receive a diploma for a Bachelor of Science, w/ Employee=student, CertificarteType=Bachelor of Science and Certificate=diploma.

I want my table to show all Employees as rows, CertificateTypes as columns and the Certificate expiry date as the cell value.

I could build a list/dict in my view, or I could try and build it in the template (I was looking at the regroup template tag). What's the best开发者_如何学编程/easiest way to do this?


To solve this problem, stick with separation of presentation from view logic. There isn't really any standard means for combining > 2 related models with template logic. The question is more or less an outer join, which is an operation that Django chooses not to support (see this question).

To answer my own question, I chose to build a custom context as a dictionary of employee, certificates key,value pairs.

Context had the format:

certs_context = { 
    employee0: [
        [
            certificatetype0_certificate0,
            certificatetype0_certificate1,
        ],
        [
            certificatetype1_certificate0,
        ],
    ],
}

As long as the certificate list for each employee key maintains the same certificate type order, it is easy to construct a table in the template using a nested loop.

Keeps the template/presentation logic (more) simple.

0

精彩评论

暂无评论...
验证码 换一张
取 消