16

I have a model like

class MyModel(models.Model):
    uuid = models.CharField(max_length=40, unique=True)

and a serializer

class MyModelSerializer(serializers.ModelSerializer):    
    class Meta:
         model = MyModel
    fields = ('uuid')

And I want to receive JSON with MyModel object but it can be existing objects. So, when I use serializer.is_valid() with data about existing object it gives me an error:

for record in request['records']: 
    # request - body of JSON request, 
    # 'records' - array of records I want to add or update

    serializer = MyModelSerializer(data=record)
    if serializer.is_valid():
        # Do stuff
        serializer.save()

Error:

 {"uuid":["This field must be unique."]}

Is there a way to separate behavior for new and existing objects? Particularly, I want to create new MyModel object if it's not it database yet and update existing MyModel object if it's present.

6
  • 1
    Can you add the code you are using for working with the serializer (usually the view) to the question? Mar 25, 2015 at 17:19
  • 1
    Added, but it's useless info because I already described - the problem is in is_valid() function. Mar 25, 2015 at 18:30
  • 1
    Can you add your complete API view code? Perhaps you are using a POST request to both create and update an instance?
    – Fiver
    Mar 25, 2015 at 23:58
  • Yes, moreover, I use only one request with array of records and I iterate them. Added for before stuff with serializer Mar 26, 2015 at 9:37
  • Did we get an answer to this? Seems the most fundamental requirement of any API framework. Currently is_valid() just breaks things for existing objects on which we intend to run update. I understand that for both PUT and POST request we can use serializer.save() and it will use create/update based on id is provided or not. Mar 14, 2019 at 11:12

2 Answers 2

5

You are basically overloading a single entry point of your REST API by trying to both create new instances and update existing instances using a POST request. In addition, it seems you are trying to create and update multiple instances simultaneously within a single POST request.

Django REST Framework (DRF) expects a POST request to only create new instances. Therefore, sending an existing instance record triggers a unique constraint violation for the uuid field since DRF tries to create that record as a new instance, as the existing instance already has that uuid value.

A solution to make your REST API more "RESTful" would be to separate the creation and updating of records into POST and PUT requests respectively. It is unclear if you are using the generic API views provided by DRF, but you can use the CreateAPIView to POST new instances, then create a separate UpdateAPIView to PUT and/or PATCH existing instances. Even better you could allow retrieval via GET for both of these endpoints using the generic views ListCreateAPIView and RetrieveUpdateAPIView.

Finally, for handling bulk requests (i.e. multi-instances in a single request) you can either override the built-in view methods or use a 3rd-party package such as django-rest-framework-bulk.

2
  • 1
    I thought we are supposed to write one serializer and override its create/update method if needed. Then use .save() which will use either create or update method based on if the id is provided or not. So the original question is still valid. Mar 14, 2019 at 11:16
  • To make the API idempotent with regarding POSTs, the behaviour of allowing update can be useful or needed. For example, I want to have an endpoint where a user can POST invites (to invite another user), as a side effect I send out an invitation. Then I wanted a second POST (with exactly the same data) to pass serializer validation even if the invite is already in the db, so I at least can re-send the invite (with no other db update). Then the serializer "smart" features worked against me in exactly this way.
    – BjornW
    Apr 27, 2020 at 15:34
3

I had a situation where I had a deep create method, with 2 levels of hierarchy above the end point, that it was important that all models were idempotent.

I override the validation in the serializer, and created it by hand.

It is important that you add the field to the class at the top (otherwise the validator won't be run)

class ParticipantSerializer(serializers.HyperlinkedModelSerializer):

    device = DeviceSerializer(required=False)
    uuid = serializers.CharField()

    def validate_uuid(self, value):
        if value is not None and isinstance(value, basestring) and len(value) < 256:
            return value
        else:
            if value is not None:
                raise serializers.ValidationError("UUID can't be none")
            elif isinstance(value, basestring):
                raise serializers.ValidationError("UUID must be a string")
            elif len(value) < 256:
                raise serializers.ValidationError("UUID must be below 256 characters")
            else:
                raise serializers.ValidationError("UUID has failed validation")

    class Meta:
        model = Participant
        fields = ("uuid", "platform", "device")
1
  • 5
    The custom validation method was not necessary for me. Just defining the serializers.CharField() fixed the problem. I think this is because it completely bypasses the models.CharField validation and uses the serializers.CharField validation instead. serializers.CharField doesn't even have a unique option and includes no validators by default. django-rest-framework.org/api-guide/fields Dec 4, 2017 at 17:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.