2011-09-09 150 views
11

我在Django幾個模型,我附上一個位置公佈每個博客:過濾外鍵在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) 

我試圖篩選他們的國家的名字,但我得到「的SyntaxError :關鍵字不能是一個表達式」當我嘗試以下方法:

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

上我可以如何根據國家名稱過濾器的任何想法?

+2

1年後,答案仍然不被接受!! – shabeer90

回答

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

btw!加拿大的岩石=) –

+5

而關於這個答案的文檔是[here](https://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships)。 –

+0

時間複雜度是多少? –