Django Tastypie - 包括许多领域

时间:2013-02-23 15:19:26

标签: django api tastypie

我正在尝试使用django tastypie但有一些麻烦。这是我的api.py:

from tastypie.resources import ModelResource
from tastypie import fields
from app.models import First, Second, Third

class FirstResource(ModelResource):
    second = fields.ToManyField('app.api.SecondResource', 'second_set', related_name='first', null=True, blank=True, full=True)

    class Meta:
        queryset = First.objects.all()
        resource_name = 'first'

class SecondResource(ModeResource):
    first = fields.ForeignKey(FirstResource, 'first', full=True)
    third = fields.ToManyField('app.api.ThirdResource', 'third_set', related_name='second', null=True, blank=True, full=True)

    class Meta:
        queryset = Second.objects.all()
        resource_name = 'second'

class ThirdResource(ModelResource):
    poll = fields.ForeignKey(SecondResource, 'second', full=True)

    class Meta:
        queryset = Third.objects.all()
        resource_name = 'third'

当我尝试使用http://127.0.0.1:8000/app/api/v1/second/获取SecondResource时,它包含FirstResource,但我也想要关联ThirdResource。  现在它只给我一个空数组。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

尝试在第三个模型中添加相关名称:

class Third(models.Model):
    second = models.ForeginKey(Second, related_name=thirds)

然后在资源中:

   class SecondResource(ModeResource):`
       first = fields.ForeignKey(FirstResource, 'first', full=True)
       third = fields.ToManyField('app.api.ThirdResource', 'thirds', null=True, blank=True, full=True)