Select_related() backwards relation - auto model population

大兔子大兔子 提交于 2020-01-13 10:54:27

问题


If I have the following model:

class Contact(models.Model)
    name = models.CharField(max_length=100)
    ...

class ContactAddress(models.Model)
    line1 = models.CharField(max_length=100)
    line2 = models.CharField(max_length=100)
    ...
    contact = models.ForeignKey(Contact)

I now want to grab all Contacts and for the address to be auto populated. What would be the best way to do this? The only way I have found so far is to filter out the Contacts I want and loop around each contact and assign this to Contact.addresses. I then use this for outputting each Contacts address within a template.

Is there a better way of doing this? Select_related() almost does what I want, but doesn't seem to be able to work in the opposite direction.

Thanks in advance for your help on this one!


回答1:


You are right, select_related only works forwards! To make more efficient reverse lookups see this!



来源:https://stackoverflow.com/questions/4621082/select-related-backwards-relation-auto-model-population

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!