Reverse Foriegnkey filtering

33 views
Skip to first unread message

Jonty Needham

unread,
Jan 27, 2016, 6:58:51 AM1/27/16
to django...@googlegroups.com
I've found a need to do this and I'm struggling. Some info seems to indicate that django doesn't support this. How is it meant to be done?

Basically to be clear, I need to filter one queryset on a reverse foriegnkey relation to another set of objects defined by a particualr filter.

model1(Models.model):
    stuff = charfield

model2(Models.model):
    cow = Foreignkey(model1)
    country = charfield


Problem: filter set of model1's by a particular country that's related to model1 through model2

Rafael E. Ferrero

unread,
Jan 27, 2016, 7:06:10 AM1/27/16
to django...@googlegroups.com
why not filter model2 with select_related ?? (you already try to put a related_name in the foreignkey of model2?)

cheers!

Rafael E. Ferrero

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CANOQRbw40C9NTiwLc_c3cT9BWLj_nDKnk76KSb1U57w0VXq_ag%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Michal Petrucha

unread,
Jan 27, 2016, 7:16:40 AM1/27/16
to django...@googlegroups.com
If I read the problem correctly, the following should solve it::

model1.objects.filter(model2__country=my_country)

Cheers,

Michal
signature.asc

Peter of the Norse

unread,
Jan 30, 2016, 2:03:41 PM1/30/16
to django...@googlegroups.com
You also might need to follow up with .distinct() https://docs.djangoproject.com/en/1.8/ref/models/querysets/#django.db.models.query.QuerySet.distinct

Peter of the Norse
Rahm...@Radio1190.org



Reply all
Reply to author
Forward
0 new messages