2016-08-03 57 views
3

我通过DRF制作了django项目。 enter image description here在DRF(django-rest-framework)中,“author_id”列中的空值违反了非空约束。我该怎么办?

从那个窗口,我点击发布,然后它没有奏效。

回溯

#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

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

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 

另外,我正在使用django休息验证。

为什么会出现此错误?如何解决这个问题?

感谢您的阅读。

回答

0

您无法在author字段中使用null创建Comment实例。 为了修复它,当你创建新的评论

class CommentSerializer(serializers.HyperlinkedModelSerializer): 
................... 

def create(self, validated_data): 
    validated_data['author'] = self.context['request'].user 
    return super(CommentSerializer, self).create(validated_data) 

post领域同样可以添加作者。

+0

非常感谢! – touchingtwist

相关问题