Home > Mobile >  Django Rest Framework - Serializer update_or_create giving IntegrityError: Unique Constraint Failed
Django Rest Framework - Serializer update_or_create giving IntegrityError: Unique Constraint Failed

Time:11-02

I am having an issue when using the API to send an update to an existing record.

When I send the API for a new record, it works perfectly. But when I send it for an existing record, I would like it to update the current record, but it just gives me an integrity error instead.

My Serializers.py looks like this:


class PartSerializer(serializers.ModelSerializer):
    part = serializers.CharField()
    class Meta:
        model = DocumentRef
        fields = ('part', 'field1', 'field2', 'field3')

    def create(self, validated_data):
        part = Part.objects.get(part_number=validated_data['part'])
        validated_data['part'] = part
        return DocumentRef.objects.update_or_create(**validated_data)

I have tried changing update_or_create to just create or just update but it will still only work if the record does not exist yet.

The model it should be referencing is DocumentRef, which looks like this:


class DocumentRef(models.Model):
    part = models.OneToOneField(Part, on_delete=models.CASCADE)
    field1 = models.FileField(upload_to='mcp/')
    field2 = models.FileField(upload_to='qcp/')
    field3 = models.FileField(upload_to='cus/')

The API View I am using is this:


class APIDetailTest(APIView):
    def get_object(self, pk):
        try:
            return DocumentRef.objects.get(pk=pk)
        except DocumentRef.DoesNotExist:
            return HttpResponse(status=status.HTTP_404_NOT_FOUND)

    def get(self, request, pk):
        part = self.get_object(pk)
        serializer = PartSerializer(part)
        return Response(serializer.data)

    def put(self, request, pk):
        part = self.get_object(pk)
        serializer = PartSerializer(part, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Edit: Changed create_or_update to update_or_create -- Just made this error in this post, in my code it was correct from the beginning.

Edit2: Have also tried changing the return value to:

return DocumentRef.objects.update_or_create(defaults={'part_id': part.id}, field1=validated_data['field1'], field2=validated_data['field2'], field3=validated_data['field3']) but that still gives the unique constraint failed error.

CodePudding user response:

Try using it with defaults and kwargs please read here: django docs

The update_or_create method tries to fetch an object from database based on the given kwargs. If a match is found, it updates the fields passed in the defaults dictionary.

CodePudding user response:

You need to update your query like this

def create(self, validated_data):
    part = Part.objects.get(part_number=validated_data['part'])
    validated_data['part'] = part
    return DocumentRef.objects.update_or_create(defaults={'part': part}, **validated_data)
  • Related