Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering on Foreign Keys in Django

Tags:

python

orm

django

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?

like image 262
Mark L Avatar asked Sep 09 '11 20:09

Mark L


Video Answer


1 Answers

blog_list = Blog.objects.filter( town__country__country_name = 'Canada' ).order_by( '-id' )
like image 54
Arthur Neves Avatar answered Oct 05 '22 17:10

Arthur Neves