Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 695
rapadura Avatar asked Nov 14 '10 22:11

rapadura


1 Answers

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!

like image 194
Bernhard Vallant Avatar answered Oct 21 '22 12:10

Bernhard Vallant