我正在使用 Django REST Framework 为我的 Web 应用程序创建 API。我有一个班级“评论”,已depth=2
在Meta
班级中设置。GET
这在ing时效果很好Comments
。当我尝试发送POST
orPUT
请求时(即创建一个新的Comment
),我被告知我需要包含对象而不是 ForeignKey ID。
这是我的序列化程序类:
class CommentSerializer(serializers.ModelSerializer):
class Meta:
model = Comment
depth = 2
该模型:
class Comment(models.Model):
user = models.ForeignKey(User, null=True, blank=True,
related_name='comments')
budget = models.ForeignKey(Budget, related_name='comments')
published = models.BooleanField(default=False)
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
视图代码:
class Comments(generics.ListCreateAPIView):
model = Comment
serializer_class = CommentSerializer
def pre_save(self, obj):
obj.user = self.request.user
输出(JSON)中显示的错误是:
{"user": ["This field is required."], "budget": [{"non_field_errors": ["Invalid data"]}]}
发送此原始数据时:
{"budget": 2, "published": true, "body": "Another comment"}