[Answered ]-Django ORM Cannot filter by reversed foreign key

1👍

You haven’t defined the fk properly:

class Foo(models.Model):
    pass

class Bar(models.Model):
    name = models.CharField()
    foo = models.ForeignKey(Foo, related_name='bars', blank=True, null=True, default=None)

To deal with circular imports:

foo = models.ForeignKey('<app_name>.Foo', related_name='bars', blank=True, null=True, default=None)

1👍

You must use related_query_name in your query filter. By default in Django 1.8 it’s model name, so set custom related_query_name or change your code to this:

Foo.objects.filter(bar__name=xyz)

Leave a comment