模型.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__"
視圖.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.
我曾多次嘗試評論特定的待辦事項。單個經過身份驗證的用戶可以對單個待辦事項寫一條評論。當我發送帖子請求時,回應顯示 無法分配 "<User: shakil>": "Comment.comment_user" must be a "Profile" instance。 我猜問題發生在該行下方: serializer.save(todo=todo_item,comment_user=user_comment)
uj5u.com熱心網友回復:
確實是因為這一行:
serializer.save(todo=todo_item,comment_user=user_comment)
user_comment是一個User實體,但正如錯誤所暗示的那樣comment_user期望一個Profile實體。
因此,如果您確實打算使用當前用戶的組態檔,則可以執行以下操作:
serializer.save(todo=todo_item, comment_user=user_comment.user)
哪里.user是相關的名稱來訪問Profile從User。(您可能希望將相關名稱更改為更好的名稱,例如profile)
uj5u.com熱心網友回復:
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/347624.html
