在Django中过滤外键

时间:2021-11-11 19:34:33

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

我在Django有一些模型,我在其中为每个发布的博客添加了一个位置:

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:

我试图在国家名称上过滤它们,但是当我尝试以下操作时,我得到了"SyntaxError:关键字不能是表达式"

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?

关于我如何根据国家名称过滤的想法?

1 个解决方案

#1


16  

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

#1


16  

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