【发布时间】:2017-11-30 21:17:22
【问题描述】:
我正在尝试使用 Django rest-framework 更新模型。
序列化器.py
class MatchSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = MatchModel
fields = ("id", "player_1", "player_2")
models.py
class MatchModel(models.Model):
player_1 = models.CharField(max_length=256)
player_2 = models.CharField(max_length=256)
views.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 更新现有的匹配
我做错了什么?
【问题讨论】:
标签: python django-rest-framework