[英]In DRF(django-rest-framework), null value in column “author_id” violates not-null constraint. What should i do?
I made django project through DRF. 我通过DRF制作了django项目。 enter image description here
在此输入图像描述
From that window, i clicked post so then it did not worked. 从那个窗口,我点击了帖子,然后它没有奏效。
traceback 追溯
#I almost omitted other codes
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/comments/
Django Version: 1.9.7
Python Version: 3.5.2
Traceback:
Exception Type: IntegrityError at /comments/
Exception Value: null value in column "author_id" violates not-null constraint
DETAIL: Failing row contains (2, comment1, 2016-08-03 13:30:59.536186+00, null, null).
serializers.py serializers.py
class UserSerializer(serializers.HyperlinkedModelSerializer):
posts = serializers.HyperlinkedRelatedField(many=True, view_name='post-detail', read_only=True)
comments = serializers.HyperlinkedRelatedField(many=True, view_name='comment-detail', read_only=True)
class Meta:
model = User
fields = ('url','id', 'pk', 'username', 'email', 'comments', 'posts', 'author')
class CommentSerializer(serializers.HyperlinkedModelSerializer):
author = serializers.ReadOnlyField(source='author.username')
post = serializers.ReadOnlyField(source='post.title')
highlight = serializers.HyperlinkedIdentityField(view_name='comment-highlight', format='html')
class Meta:
model = Comment
fields = ('url','id', 'pk', 'post', 'author', 'text','highlight')
models.py models.py
class Comment(models.Model):
post = models.ForeignKey('blog.Post', related_name='related_comments')
author = models.ForeignKey(User, related_name='related_commentwriter')
text = models.TextField(max_length=500)
created_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.text
Additionally, i'm using django rest auth. 另外,我正在使用django rest auth。
Why this error comes? 为什么会出现此错误? How to solve this?
怎么解决这个?
Thanks for reading. 谢谢阅读。
You could not create Comment instance with null in author
field. 您无法在
author
字段中使用null创建Comment实例。 For fix it you can add author when you create new comment 要修复它,您可以在创建新注释时添加作者
class CommentSerializer(serializers.HyperlinkedModelSerializer):
...................
def create(self, validated_data):
validated_data['author'] = self.context['request'].user
return super(CommentSerializer, self).create(validated_data)
The same with post
field. 与
post
field相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.