django rest框架中的IntegrityError

时间:2014-08-28 23:16:33

标签: python django django-rest-framework

我正在玩DRF并制作了一个简单的博客,匿名人士可以在博客上发表评论。我现在只是使用可浏览的API,在我尝试发表评论之前,一切似乎都正常。 DELETE,GET和PUT都按预期工作,只有POST。

我得到的错误是IntegrityError at /api/posts/i-had-a-blog-his-name-was-bingo/comments/: blog_comment.blogpost_id may not be NULL

我已经彻底搜索了为什么会发生这种情况的答案,但没有任何帮助。这是我的代码......

models.py

class BlogPost(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    owner = models.ForeignKey('auth.User', related_name='posts')
    title = models.CharField(max_length=100, unique=True)
    content = models.TextField()
    slug = models.SlugField(max_length=100, unique=True, editable=False)
    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(BlogPost, self).save(*args, **kwargs)
    @permalink
    def get_absolute_url(self):
        return ('post-detail', { 'slug': self.slug })
    class Meta:
        ordering = ('created',)

class Comment(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    blogpost = models.ForeignKey(BlogPost, related_name='comments')
    author = models.CharField(max_length=100, blank=False)
    content = models.TextField()
    class Meta:
        ordering = ('created', 'author', 'content')

serializers.py

class CommentSerializer(serializers.HyperlinkedModelSerializer):
    post = serializers.Field(source='blogpost.title')

    class Meta:
        model = Comment
        fields = ('id', 'author', 'content', 'post')    


class BlogPostSerializer(serializers.HyperlinkedModelSerializer):
    owner = serializers.Field(source='owner.username')
    url = serializers.HyperlinkedIdentityField(view_name='post-detail')
    comments = serializers.HyperlinkedIdentityField(view_name='comment-list')

    class Meta:
        model = BlogPost
        fields = ('url', 'id', 'title', 'content', 'owner', 'comments')

views.py

class CommentList(generics.ListCreateAPIView):
    serializer_class = CommentSerializer

    def get_queryset(self):
        slug = self.kwargs['slug']
        return Comment.objects.filter(blogpost__slug=slug)


class CommentDetail(generics.RetrieveUpdateDestroyAPIView):
    serializer_class = CommentSerializer
    permission_classes = (IsAdminOrNoEdit,)

    def get_queryset(self):
        slug = self.kwargs['slug']
        return Comment.objects.filter(blogpost__slug=slug)

urls.py

commentpatterns = patterns('',
    url(r'^$', views.CommentList.as_view(), name='comment-list'),
    url(r'^(?P<pk>[0-9]+)/$', views.CommentDetail.as_view(), name='comment-detail'),
)


urlpatterns = patterns('blog.views',
    url(r'^$', 'api_root'),
    url(r'^posts/$', views.PostList.as_view(), name='post-list'),
    url(r'^posts/(?P<slug>[-\w]+)/$', views.PostDetail.as_view(), name='post-detail'),
    url(r'^posts/(?P<slug>[-\w]+)/comments/', include(commentpatterns)),
    url(r'^users/$', views.UserList.as_view(), name='user-list'),
    url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view(), name='user-detail'),
)

任何帮助将不胜感激,这让我发疯。

1 个答案:

答案 0 :(得分:4)

您的Comment模型定义了ForeignKey,不允许null

class Comment(models.Model):
    ...
    blogpost = models.ForeignKey(BlogPost, related_name='comments')
    ...

这没关系,但你的序列化程序不包含blogpost id,所以即使你的请求包含它,它也会被忽略。更正序列化程序以包含blogpost字段:

class CommentSerializer(serializers.HyperlinkedModelSerializer):
    post = serializers.Field(source='blogpost.title')
    blogpost = serializers.PrimaryKeyRelatedField()

    class Meta:
        model = Comment
        fields = ('id', 'author', 'content', 'post', 'blogpost')

现在,当您创建发布请求时,blogpost字段应包含您附加此评论的博客帖子的id