gpt4 book ai didi

django-rest-framework - 尝试在序列化程序 `opponent` 上获取字段 `DialogSerializer` 的值时出现 AttributeError

转载 作者:行者123 更新时间:2023-12-02 19:53:09 29 4
gpt4 key购买 nike

在serializer.py中使用create方法后出现错误

这是我的错误:

Got AttributeError when attempting to get a value for field opponent on serializer DialogSerializer. The serializer field might be named incorrectly and not match any attribute or key on the tuple instance. Original exception text was: 'tuple' object has no attribute 'opponent'.

这是我的serializer.py

class DialogSerializer(serializers.ModelSerializer):
"""A serializer for profile feed items."""
def create(self, validated_data):
dialog=Dialog.objects.get_or_create(**validated_data)
return dialog
class Meta:
model = Dialog
fields = ('id', 'owner','opponent')
extra_kwargs = {'owner': {'read_only': True}}



class DialogueViewSet(viewsets.ModelViewSet):

serializer_class = DialogSerializer
permission_classes = (IsAuthenticated,)

def get_queryset(self):


user=self.request.user

return Dialog.objects.filter(owner=user)

def perform_create(self, serializer):
"""Sets the user profile to the logged in user."""

serializer.save(owner=self.request.user)
# def create(self,**kwargs):

最佳答案

主要问题是 get_or_create(object, created) 一样返回元组。所以下面的事情应该可以解决你的问题。

 def create(self, validated_data):
dialog, created =Dialog.objects.get_or_create(**validated_data)
return dialog

关于django-rest-framework - 尝试在序列化程序 `opponent` 上获取字段 `DialogSerializer` 的值时出现 AttributeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57729767/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com