开发者

Confused about basic multiple-table relation & access using Django

I have a few data models (tabl开发者_如何学Goes) 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 ForeignKey field on one model, the target model automatically gets a attribute called <referring_model>_set - so in your example, each Company instance has a location_set attribute, and each Location has a contact_set attribute. These attributes actually refer to Manager instances, similar to Company.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.:

<ul>
{% for location in company.location_set %}
    <li>
        <em>{{ location.name }}</em>
        <ul>
        {% for contact in location.contact_set %}
            <li>{{ contact.name }}</li>
        {% endfor %}
        </ul>
    </li>
{% endfor %}
</ul>

You can read more about this kind of backwards relationship in the Django docs.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜