gpt4 book ai didi

python - Django Rest-Framework 序列化程序忽略模型 ID

转载 作者:行者123 更新时间:2023-12-01 02:24:02 24 4
gpt4 key购买 nike

我正在尝试使用 Django Rest-framework 更新模型。

序列化器.py

class MatchSerializer(serializers.HyperlinkedModelSerializer):       
class Meta:
model = MatchModel
fields = ("id", "player_1", "player_2")

模型.py

class MatchModel(models.Model):                                 
player_1 = models.CharField(max_length=256)
player_2 = models.CharField(max_length=256)

View .py

class MatchesViewSet(APIView):  

...

def put(self, request, format=None):
serializer = self.serializer_class(data=json.loads(request.body))
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data)

请求是这样生成的:

match = {                                                                         
"id": 1,
"player_1": "updatedP1",
"player_2": "updatedP2",
}
r = self.c.put("/api/matches", json.dumps(match), content_type="application/json")

但是它不断添加新的匹配项,而不是使用 id=1 更新现有的匹配项

我做错了什么?

最佳答案

如果您希望serializer.save()更新现有实例,则需要在实例化序列化器类时传递它,例如:

def put(self, request, format=None):
data = json.loads(request.body)
instance = get_object_or_404(MatchModel, pk=data["id"])
serializer = self.serializer_class(instance, data=data)
...

检查Saving instances更多细节。

PS,您可能还想为单个匹配使用单独的资源(例如 /api/matches/1),而不是单个 /api/matches

关于python - Django Rest-Framework 序列化程序忽略模型 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47582764/

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