我对POST请求视图有疑问。
如果我不将序列化器(AnswerSurveySerializer)设置为(many = True),但我只想为该字段发布一个外键项,则DRF将引发属性错误。
提前感谢您的任何建议和感谢。
models.py
class Survey(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='surveys',
on_delete=models.CASCADE)
is_completed = models.BooleanField(default=False)
def __str__(self):
return self.status
class Answer(models.Model):
history = HistoricalRecords()
survey = models.ForeignKey(
Survey, related_name='answers', on_delete=models.CASCADE)
choice = models.ForeignKey(
Choice, related_name='answers', on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
serializers.py
class AnswerSurveySerializer(serializers.ModelSerializer):
class Meta:
model = models.Survey
fields = ('id',)
class AnswerSerializer(serializers.ModelSerializer):
survey = AnswerSurveySerializer(many=True)
class Meta:
model = models.Answer
fields = ('survey',)
views.py
class AddAnswerView(generics.CreateAPIView):
"""Handles creating answers to MCQ."""
serializer_class = AnswerSerializer
答案 0 :(得分:1)
问题出在您的 __str__
模型的 Survey
方法中。 __str__
方法返回( 试图返回 )属性status
,但是Survey
模型类没有{{1 }}。
因此,从模型中删除 status
方法或更改为有意义的内容,例如
__str__