2012-11-07 70 views
3

我想通過相關字段pk篩選資源。Tastypie - 通過相關pk篩選

例如,我有國家PK,我想從該國獲得所有城市。我怎麼能這樣做?

class CityResource(ModelResource): 
    class Meta: 
     queryset = City.objects.all() 
     resource_name = 'city' 
     fields = ['name','id'] 

     filtering = { 
      #Something here 
     } 

class CountryResource(ModelResource): 
    class Meta: 
     queryset = Country.objects.all() 
     resource_name = 'country' 
     fields = ['name','code2','id'] 

而且一個例子網址:

http://startuprepublik.pre.is/api/v1/city/?format=json&country__pk=4 

任何想法?

+0

你在你的城市模型上有國家ForeignKey嗎? – andrefsp

+0

是的。我正在使用cities_light。 https://github.com/yourlabs/django-cities-light/blob/master/cities_light/models.py –

回答

3
from tastypie.fields import ForeignKey 
from tastypie.resources import ALL_WITH_RELATIONS 

class CityResource(ModelResource): 
    country = ForeignKey("path.to.api.CountryResource", "country") 

    class Meta: 
     queryset = City.objects.all() 
     resource_name = 'city' 
     fields = ['name','id'] 

     filtering = { 
      "country": ALL_WITH_RELATIONS 
     } 

class CountryResource(ModelResource): 
    class Meta: 
     queryset = Country.objects.all() 
     resource_name = 'country' 
     fields = ['name','code2','id'] 
     filtering = { "id": ALL } 
+0

嗨Issac。我得到這個迴應>'國家'字段不允許過濾。我試圖在CountryResource上添加一個過濾變量,但我得到了相同的結果。 –

+2

好的。我解決了它,似乎沒有重新啓動服務器或其他東西。如果我想補充: 過濾= { 「ID」:ALL, } 它解決了這個問題,你可以更新你的答案,所以我可以將其標記爲解決?謝謝! –

+0

謝謝Mc-,這個評論拯救了我 – Tsangares