[英]Django reverse lookup by ForeignKey
I have a django project which has two apps, one is AppA
and AppB
. 我有一个django项目,它有两个应用程序,一个是
AppA
和AppB
。 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.