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 ModelB
s 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 ModelB
s 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
!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With