簡體   English   中英

Django-tastypie一對多的關系

[英]Django-tastypie One-To-Many relationship

我正在嘗試創建一個具有0到無限注釋的資源(觀察)。 我遇到了以下錯誤:

"error": "The model '<Observation: Observation object>' has an empty attribute 'comments' and doesn't allow a null value."

此外,將null = True添加到comments =(...)將導致空注釋對象,即使應該有相關觀察的注釋。

我也嘗試通過將其更改為完整路徑來搞亂CommentResource2路徑。

我一直在關注Tastypie文檔中的反向關系指南:

扭轉“關系”

這是我的模特:

class Observation(ObsModel):
    taxon_node = models.ForeignKey(TaxonNode, related_name = 'observation_taxon_node', null = True)
    substrate = models.ForeignKey(TaxonNode, related_name = 'observation_substrate', null = True, blank=True)
    source = models.CharField(max_length=255, blank=True)
    sample = models.ForeignKey(Sample)
    remarks = models.TextField(blank = True)
    exact_time = models.DateTimeField(null=True)
    individual_count = models.IntegerField(null = True)
    is_verified = models.NullBooleanField(null = True)
    verified_by = models.ForeignKey(User, null = True)
    verified_time = models.DateTimeField('time verified', null = True)

    class Meta():
        app_label = 'observation'


class Comment(models.Model):
    observation = models.ForeignKey(Observation)
    comment = models.TextField()
    created_time = models.DateTimeField('time created', auto_now_add=True, editable=False)

    class Meta:
        app_label = 'observation_moderate'

和資源:

class ObservationResource2(ModelResource):
    comments = fields.ToManyField('apps.api.CommentResource2', 'comments')
    class Meta:
        queryset = Observation.objects.filter(is_verified=False)
        authentication = SessionAuthentication()
        authorization = DjangoAuthorization()
        resource_name = 'observation'

class CommentResource2(ModelResource):
    observation = fields.ToOneField(ObservationResource2, 'observation')
    class Meta:
        queryset = Comment.objects.all()
        resource_name = 'comments'
        authentication = SessionAuthentication()
        authorization = DjangoAuthorization()

您缺少觀察模型上的“評論”屬性,要么添加

observation = models.ForeignKey(Observation, related_name="comments")

或改為

comments = fields.ToManyField('apps.api.CommentResource2', 'comment_set', null=True)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM