【发布时间】:2013-03-30 19:19:26
【问题描述】:
我正在使用 Django REST Framework 为我的 Web 应用程序创建 API。我有一个“评论”类,它在Meta 类中设置了depth=2。当GETComments 时,这很有效。当我尝试发送POST 或PUT 请求时(即创建一个新的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"}
【问题讨论】:
-
随机提问,发
{"budget_id": 2}或{"budget": {"id": 2}}怎么办? -
RE @Nathan Villaescusa。然后它会根据需要显示其他预算字段。
标签: python django rest django-rest-framework