[Django]-IntegrityError in django rest framework

4👍

Your Comment model defines a ForeignKey, which is not allowed to be null:

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

which is ok, but your serializer does not include the blogpost id, so even if your request includes it, it will be just ignored. correct your serializer to include the blogpost field:

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

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

now when you create a post request, the blogpost field should contain the id of the blog post to which you’re attaching this comment.

Leave a comment