I have a few data models (tables) which are associated with each other. If a model has a related field pointing to another model, no problem, i can access that easy in the templates but how do I make calls that have reverse-only relation?
Example:
Company may have any number of Location and each Location may have any number of Contact.
So the Company table mentions neither the Location or Contact, but Location has a fk to Company. and Contact has a fk to Location.
In the template, I’d like to display Companies that match certain criteria. With them, I’d like their locations and their locations contacts to also display.
My thought is, maybe I make the Company query first, then make another for Location (and Contact) and some how inject them into the same dict but that sounds awfully confusing to me and this, im sure, is a common pattern.
Any tips?
When you make a
ForeignKeyfield on one model, the target model automatically gets a attribute called<referring_model>_set– so in your example, eachCompanyinstance has alocation_setattribute, and eachLocationhas acontact_setattribute. These attributes actually refer toManagerinstances, similar toCompany.objects, that return only objects related to the current instance.You can use these backwards references to iterate through the related objects in your templates, e.g.:
You can read more about this kind of backwards relationship in the Django docs.