如何让tastypie对外键进行反向查找?

时间:2014-06-03 16:25:28

标签: django tastypie

我有两个django模型:生物学和发生。他们有一对一的关系。生物学模型具有发生的外键,并且tastypie生物学资源遵循这种关系并正确地显示相应的发生数据。我试图让反向查找在API中工作。当我尝试访问occurrenceResource时,出现错误

"error: "The model '2' has an empty attribute 'occurrence' and doesn't allow a null value.""

我的tastypie资源类看起来像这样

class biologyResource(ModelResource):
    occurrence = fields.ToOneField("API.API_resources.occurrenceResource", "occurrence")
    class Meta:
        queryset = biology.objects.all()
        resource_name = 'biology'


class occurrenceResource(ModelResource):
    biology = fields.ToOneField("API.API_resources.biologyResource", "id", full=True)
    class Meta:
        queryset = occurrence.objects.all()
        resource_name = 'occurrence'

我见过some similar stackoverflow questions,但他们主要处理的是多对多关系。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

在这种情况下,有一条规则非常有用。几乎总是资源字段的属性是模型字段的属性。

如果您的模型有字段:

my_field = model.WhateverField()

因此,资源定义必须具有:

my_field = fields.WhateverField(" Whatever",attribute =" my_field ")

如何通过发生来获取生物学?

>>> biology_object.occurrence # I assume your model name is `Occurrence`

以其他方式:

>>> occurrence_object.biology # I assume your model name is `Biology`

所以occurrencebiology是模型的属性,换句话说它们是属性。

class biologyResource(ModelResource):
    occurrence = fields.ToOneField("API.API_resources.occurrenceResource", attribute="occurrence")
    class Meta:
        queryset = biology.objects.all()
        resource_name = 'biology'


class occurrenceResource(ModelResource):
    biology = fields.ToOneField("API.API_resources.biologyResource", attribute="biology", full=True)
    class Meta:
        queryset = occurrence.objects.all()
        resource_name = 'occurrence'

如果遇到问题,请复制粘贴模型。