Skip to content
Advertisement

Django Query with 3 tables

I’m hoping I can get a little guidance.

I’m trying to return data from 3 related tables in my template. In SQL, this is a simple approach, but the Django requirements have me stumbling.

I’d like to display information similar to this:

JavaScript

Here are a simplified representation of the models with the relationships defined.

JavaScript

Here is my simplified view:

JavaScript

And, this is my template.

JavaScript

I would be very appreciative of details in the explanations as I really want to understand how this all works.

Advertisement

Answer

Firstly, for every Foreign key you are creating I suggest you to add a related_name this way you specify the name of reverse relation ship between the children model and parent model in your case for example, your code should be:

JavaScript

and let’s explain how does it work, you want to know and get all the minors of some adult, what you should do is specify the adult, and get all minor related to that adult, in code context (try it in django shell, using python manage.py shell):

JavaScript

same thing apply to the last model CheckIns.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement