Select_related()向后关系 - 自动模型人口 [英] Select_related() backwards relation - auto model population

查看:75
本文介绍了Select_related()向后关系 - 自动模型人口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下模型:

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)

我现在想抓住所有联系人,并且地址被自动填充。这样做最好的方法是什么?目前我发现的唯一方法是过滤掉我想要的联系人,并围绕每个联系人循环并将其分配给Contact.addresses。然后我使用它来输出模板中的每个联系人地址。

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.

有更好的方法吗? Select_related()几乎完成了我想要的,但似乎无法在相反的方向上工作。

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.

提前感谢您的帮助! / p>

Thanks in advance for your help on this one!

推荐答案

你是对的, select_related 只能向前推进!为了使更有效的反向查找参见这个

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

这篇关于Select_related()向后关系 - 自动模型人口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆