简体   繁体   English

外键的Django反向查找

[英]Django reverse lookup by ForeignKey

I have a django project which has two apps, one is AppA and AppB . 我有一个django项目,它有两个应用程序,一个是AppAAppB Now AppA has a model ModelA which is referenced by the model ModelB in AppB , using modelA = models.ForeignKey(ModelA, related_name='tricky') 现在, AppA有一个模型ModelA ,它由ModelB中的模型ModelB AppB ,使用modelA = models.ForeignKey(ModelA, related_name='tricky')

Now in my view for AppA , when it shows ModelA , I do a get_object_or_404(ModelA, pk=prim_id) . 现在在AppA视图中,当它显示ModelA ,我会执行get_object_or_404(ModelA, pk=prim_id) Then I want to get all the ModelB s which have a Foreign Key pointing to ModelA . 然后,我想所有的ModelB S的有一个外键指向ModelA

Documentation says I should do a mb = ModelB.objects.get(pk=prim_id) then mb.modela_set.all() 文档说我应该做一个mb = ModelB.objects.get(pk=prim_id)然后mb.modela_set.all()

But, it failed on the mb.modela_set , and it says "ModelB object has no attribute 'suchsuch'" . 但是,它在mb.modela_set上失败了,它说"ModelB object has no attribute 'suchsuch'" Notice I added the related_name field to ForeignKey, so I tried with that as well, including mb.tricky.all() and mb.tricky_set.all() to no avail. 注意我将related_name字段添加到ForeignKey,所以我也尝试了它,包括mb.tricky.all()mb.tricky_set.all()无济于事。

Oh, and I have specified a different manager for AppA where I do objects = MyManager() which returns the normal query but with a filter applied. 哦,我已经为AppA指定了一个不同的管理器,我在其中执行objects = MyManager() ,它返回正常查询但应用了过滤器。

What could be the problem? 可能是什么问题呢? What is the prefered way to get the ModelB s referencing ModelA ? ModelB引用ModelA的首选方法是什么?

If the ForeignKey is, as you describe in ModelB and you do mb = ModelB.objects.get(pk=prim_id) then the look up for the modela attribute is not a reverse lookup . 如果ForeignKey是,当你在描述ModelB和你mb = ModelB.objects.get(pk=prim_id)然后抬头对modela属性不是反向查找 you simply access the related object via mb.modela ! 你只需通过mb.modela访问相关对象!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM