Pass full instance for API PATCH operations (#126)

This is necessary in order to allow partial updates of entries but also
provide full context for model `clean()`` methods that use multiple fields.
This commit is contained in:
Christopher C. Wells 2020-03-13 20:00:32 -07:00 committed by Christopher Charbonneau Wells
parent 0c086e6469
commit 76b7e90396
1 changed files with 10 additions and 2 deletions

View File

@ -1,4 +1,5 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from copy import deepcopy
from rest_framework import serializers from rest_framework import serializers
from django.contrib.auth.models import User from django.contrib.auth.models import User
@ -15,8 +16,15 @@ class CoreModelSerializer(serializers.HyperlinkedModelSerializer):
queryset=models.Child.objects.all()) queryset=models.Child.objects.all())
def validate(self, attrs): def validate(self, attrs):
instance = self.Meta.model(**attrs) # Ensure that all instance data is available for partial updates to
instance.clean() # support clean methods that compare multiple fields.
if self.partial:
new_instance = deepcopy(self.instance)
for attr, value in attrs.items():
setattr(new_instance, attr, value)
else:
new_instance = self.Meta.model(**attrs)
new_instance.clean()
return attrs return attrs