问题
I'm trying to create a resource (Observation) that has 0 to unlimited comments. I'm stuck at the following error:
"error": "The model '<Observation: Observation object>' has an empty attribute 'comments' and doesn't allow a null value."
Also, adding null=True to comments = (...) will result in empty comment objects even though there should be comments for observations in question.
I've also tried messing around with CommentResource2 path by changing it to full path.
I've been following the reverse relationship guide from Tastypie's documentation:
Reverse “Relationships”
Here are my models:
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'
And resources:
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()
回答1:
You are missing the "comments" attribute on the Observation model, either add
observation = models.ForeignKey(Observation, related_name="comments")
or change to
comments = fields.ToManyField('apps.api.CommentResource2', 'comment_set', null=True)
来源:https://stackoverflow.com/questions/15999188/django-tastypie-one-to-many-relationship