简体   繁体   中英

Filtering on Foreign Keys in 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM