tastypie:model有一个空属性 - 反向关系

时间:2014-12-10 14:03:09

标签: python django tastypie

我使用tastypie获取此错误并尝试让ToManyField工作(它不应返回任何空值):

error: "The model 'Feature: Feature object' has an empty attribute 'featureloc_set' and doesn't allow a null value."

这些是模型:

class Feature(models.Model):
    feature_id = models.AutoField(primary_key=True)
    class Meta:
        db_table = 'feature'

class Featureloc(models.Model):
    featureloc_id = models.AutoField(primary_key=True)
    feature = models.ForeignKey(Feature, related_name="featureloc_feature")
    srcfeature = models.ForeignKey(Feature, blank=True, null=True, related_name="featureloc_srcfeature")
    class Meta:
        db_table = 'featureloc'

这些是资源:

class BFeatureResource(ModelResource):
    featurelocs = fields.ToManyField('api.BFeaturelocResource2', 'featureloc_set', full=True)
    class Meta:
        resource_name = 'bands'
        queryset = Feature.objects.all()

class BFeaturelocResource2(ModelResource):
    feature = fields.ForeignKey(BFeatureResource, 'feature')

    class Meta:
        resource_name = 'featurelocs'
        queryset = Featureloc.objects.all()

是否因为Featureloc中有2个ForeingKey字段(即feature和srcfeature)而感到困惑?我错了什么?

1 个答案:

答案 0 :(得分:1)

现在通过在ForeignKey上使用与ToManyField中的属性匹配的related_name来实现此功能:

featurelocs = fields.ToManyField('api.BFeaturelocResource2', 'fl_feature', full=True)

feature = fields.ForeignKey(BFeatureResource, 'feature', related_name='fl_feature')