【问题标题】:Cannot assign "<User: shakil>": "Comment.comment_user" must be a "Profile" instance无法分配“<用户:shakil>”:“Comment.comment_user”必须是“个人资料”实例
【发布时间】:2021-11-03 05:47:26
【问题描述】:

models.py


  from django.contrib.auth.models import User
 
     class Profile(models.Model):
         name = models.OneToOneField(User,on_delete=models.CASCADE,related_name='user')
         bio = models.CharField(max_length=300)
         photo = models.ImageField(upload_to='images/profile_photos/')
     
         def __str__(self):
             return self.name.username
     class Comment(models.Model):
         comment_user = models.ForeignKey(Profile, on_delete=models.CASCADE)
         comment_text = models.TextField(blank=True)
         todo = models.ForeignKey(Todo, on_delete=models.CASCADE,related_name='comment')
         created = models.DateTimeField(auto_now_add=True)
         updated = models.DateTimeField(auto_now=True)
         active = models.BooleanField(default=False)
 
         def __str__(self):
             return self.comment_text +" "+ self.comment_user.name.username

序列化器.py

class CommentSerializer(ModelSerializer):
    comment_user = serializers.StringRelatedField(read_only=True)
    class Meta:
        model = Comment
        exclude = ('todo',)
        #fields = "__all__"

views.py

class CommentCreateApiView(generics.CreateAPIView):
    serializer_class = CommentSerializer
    #permission_classes = [TodoCreatorOrReadOnly]
    # def get_queryset(self):
    #     return Comment.objects.all()
    def perform_create(self, serializer):
        id = self.kwargs['todo_id']
        todo_item = Todo.objects.get(pk=id)
        user_comment = self.request.user
        print(user_comment)
        comment_query = Comment.objects.filter(todo=todo_item,comment_user__name__username=user_comment).exists()
        if comment_query:
            raise ValidationError('User Comment is already exist..!')
        else:
           serializer.save(todo=todo_item,comment_user=user_comment)


错误

 File "D:\python_projects\todo_project\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 215, in __set__
    raise ValueError(
ValueError: Cannot assign "<User: shakil>": "Comment.comment_user" must be a "Profile" instance.

我曾多次尝试评论特定的待办事项。 单个经过身份验证的用户可以在单个待办事项上写一条评论。 当我发送帖子请求时,响应显示 无法分配“”:“Comment.comment_user”必须是“Profile”实例。 我猜问题发生在下面的行内: serializer.save(todo=todo_item,comment_user=user_comment)

【问题讨论】:

    标签: python django django-rest-framework django-serializer


    【解决方案1】:

    确实是因为这行:

    serializer.save(todo=todo_item,comment_user=user_comment)
    

    user_commentUser 实例,但 comment_user 需要 Profile 实例,如错误所示。

    因此,如果您确实打算使用当前用户的个人资料,您可以这样做:

    serializer.save(todo=todo_item, comment_user=user_comment.user)
    

    其中.user 是从User 访问Profile 的相关名称。 (您可能希望将相关名称更改为更好的名称,例如 profile

    【讨论】:

    • 你节省了我的时间。非常感谢您提供完整解释的答案。
    • 如果对您有帮助,请回答accept 和/或vote
    【解决方案2】:

    view.py

    class CommentCreateApiView(generics.CreateAPIView):
        serializer_class = CommentSerializer
        #permission_classes = [TodoCreatorOrReadOnly]
        # def get_queryset(self):
        #     return Comment.objects.all()
        def perform_create(self, serializer):
            id = self.kwargs['todo_id']
            todo_item = Todo.objects.get(pk=id)
            user_comment = self.request.user
            print(user_comment)
            comment_query = Comment.objects.filter(todo=todo_item,comment_user__name__username=user_comment).exists()
            if comment_query:
                raise ValidationError('User Comment is already exist..!')
            else:
               serializer.save(todo=todo_item, comment_user=user_comment.user)
    

    【讨论】:

      猜你喜欢
      • 2021-02-15
      • 1970-01-01
      • 2020-12-05
      • 2021-11-18
      • 1970-01-01
      • 1970-01-01
      • 2011-02-22
      • 2018-06-03
      相关资源
      最近更新 更多