Home » Django » Filtering on Foreign Keys in Django

Filtering on Foreign Keys in Django

Posted by: admin December 31, 2017 Leave a comment

Questions:

I have a few models in Django where I attach a location to each blog published:

class Country(models.Model):
    country_name = models.TextField()

class Town(models.Model):
    country = models.ForeignKey(Country)
    town_name = models.CharField(max_length=192)

class Blog(models.Model):
    town = models.ForeignKey(Town)

I’m trying to filter them on country name but I’m getting “SyntaxError: keyword can’t be an expression” when I try the following:

blog_list = Blog.objects.filter( town.country.country_name = 'Canada' ).order_by( '-id' )

Any ideas on how I could filter based on the country name?

Answers:
blog_list = Blog.objects.filter( town__country__country_name = 'Canada' ).order_by( '-id' )