开发者

Django reverse lookup by ForeignKey

I have a django project which has two apps, one is AppA and AppB. Now AppA has a model ModelA which is referenced by the model ModelB in AppB, using 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). Then I want to get all the ModelBs which have a Foreign Key pointing to ModelA.

Documentation says I should do a mb = ModelB.objects.get(pk=prim_id) then mb.modela_set.all()

But, it failed on the mb.modela_set, and it says "ModelB object has no attribute 'suchsuch'". Notice I added the related_name开发者_StackOverflow中文版 field to ForeignKey, so I tried with that as well, including mb.tricky.all() and mb.tricky_set.all() to no avail.

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.

What could be the problem? What is the prefered way to get the ModelBs referencing 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. you simply access the related object via mb.modela!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜