Reputation: 516
I'm trying to update a model using Django rest-framework.
serializers.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)
The request is generated like this:
match = {
"id": 1,
"player_1": "updatedP1",
"player_2": "updatedP2",
}
r = self.c.put("/api/matches", json.dumps(match), content_type="application/json")
But the thing keeps adding a new match, instead of updating the existing match with id=1
What am I doing wrong?
Upvotes: 1
Views: 926
Reputation: 149736
If you want serializer.save()
to update an existing instance, you need to pass it when instantiating the serializer class, e.g.:
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)
...
Check Saving instances for more details.
PS, you may also want to use separate resources for individual matches (e.g. /api/matches/1
) instead of the single /api/matches
.
Upvotes: 2