gpt4 book ai didi

Django-tastypie 一对多关系

转载 作者:行者123 更新时间:2023-12-04 06:40:48 26 4
gpt4 key购买 nike

我正在尝试创建一个具有 0 到无限评论的资源(观察)。我陷入了以下错误:

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

此外,将 null=True 添加到 comments = (...) 将导致空的评论对象,即使应该有相关观察的评论。

我还尝试通过将 CommentResource2 路径更改为完整路径来处理它。

我一直在遵循 Tastypie 文档中的反向关系指南:

Reverse “Relationships”

这是我的模型:
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)

关于Django-tastypie 一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15999188/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com