Django Tastypie:按ForeignKey过滤

时间:2015-05-04 02:57:05

标签: python django tastypie

我希望Django Tastypie返回一个由ForeignKey过滤的查询。这是我的两个模型:

class Origin(models.Model):
    country = models.CharField(max_length=1024)

class Fruits(models.Model):
    origin      = models.ForeignKey(Origin)
    fruit_name  = models.CharField(max_length=1024)
    is_sweet    = models.BooleanField()
    quantity    = models.IntegerField()

根据文档here,我使用以下resources.py:

class FruitResource(ModelResource):
    class Meta:
        queryset = Fruits.objects.all()
        allowed_methods = ['get']      
        filtering = {
            "origin": ('exact',)
            }

这是我要访问的网址:

http://localhost:8000/api/v1/fruit/?format=json&origin__country=Nepal

访问该URL会返回以下输出:

{
  "meta": 
    {
      "limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 2}, "objects": 
        [
          {"fruit_name": "Apple", "id": 1, "is_sweet": true, "quantity": 10, "resource_uri": "/api/v1/fruit/1/"}, 
          {"fruit_name": "Banana", "id": 2, "is_sweet": true, "quantity": 10, "resource_uri": "/api/v1/fruit/2/"}
        ]
}

我应该提一下,我使用此URL获得相同的输出:

http://localhost:8000/api/v1/fruit/?format=json

通过指定Origin的country属性来获取Fruits对象列表的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

我能够根据this answer让它运转起来。我在这里列出了最终的代码,以造福他人。

from tastypie.resources import ModelResource, fields, ALL_WITH_RELATIONS

from fruits.models import Fruits
from origin.models import Origin

class OriginResource(ModelResource):
    class Meta:
        queryset = Origin.objects.all()
        resource_name = 'origin'
        filtering = {
            "country": ('exact',)
            }

class FruitResource(ModelResource):
    origin = fields.ForeignKey(OriginResource, 'origin', full=True)
    class Meta:
        queryset = Fruits.objects.all()
        allowed_methods = ['get']
        filtering = {
            "origin": ALL_WITH_RELATIONS,
            }

使用此代码,如果我点击http://localhost:8000/api/v1/fruit/?format=json&origin__country=Nepal,我会得到以下预期输出:

{"meta": 
  {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 1},
   "objects": [{
         "fruit_name": "Apple", "id": 1, "is_sweet": true, "origin":
         {"country": "Nepal", "id": 3, "resource_uri": ""},
         "quantity": 10, "resource_uri": "/api/v1/fruit/1/"
    }]
}