Django: Query one to many relationship for existing relationship with certain attributes in the many-model

3.6k Views Asked by At

Lets say I have the following two models

Group(Model):
    attribute = CharField()

TranslatedFoo(Model):
    language = ForeignKey(Language)
    country = ForeignKey(Country)
    group = ForeignKey(Group)

Now I want to find all Groups, that have a TranslatedFoo in their translatedfoo_set with language_code='x' and country='y' in one query. Does something exist like:

Group.objects.filter(translatedfoo_set__language__code='x', translatedfoo_set__country__code='y')

I know this doesn't work. Maybe I need to rethink my table layout

1

There are 1 best solutions below

0
On BEST ANSWER

The correct query does not include the _set part:

Group.objects.filter(translatedfoo__language_code='x', translatedfoo__country='y')

Search for "reverse" on this doc page for more details.