Django-tastypie一对多的关系

Obv*_*Cat 8 django django-models tastypie

我正在尝试创建一个具有0到无限注释的资源(观察).我遇到了以下错误:

"error": "The model '<Observation: Observation object>' has an empty attribute 'comments' and doesn't allow a null value."
Run Code Online (Sandbox Code Playgroud)

此外,将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'
Run Code Online (Sandbox Code Playgroud)

和资源:

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()
Run Code Online (Sandbox Code Playgroud)

krs*_*krs 11

您缺少观察模型上的"评论"属性,要么添加

observation = models.ForeignKey(Observation, related_name="comments")
Run Code Online (Sandbox Code Playgroud)

或改为

comments = fields.ToManyField('apps.api.CommentResource2', 'comment_set', null=True)
Run Code Online (Sandbox Code Playgroud)