3

我想通过相关字段 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

任何的想法?

4

1 回答 1

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 }
于 2012-11-08T00:34:00.750 回答