0

I have a model that represents a device identifier and I'd like to create a unique constraint on the device identifier and the current user. I was passing the user on the save method but I had to remove the constraint and now that I'm trying to write tests the poor code that I wrote becomes difficult to test. How can I write a serializer where I could set the currentuser as default and mantain the unique contrasint on the model.

This is my model

class DeviceIdentifier(models.Model):
    owner = models.ForeignKey(HDSAuthUser, primary_key=True, on_delete=models.CASCADE)
    id_device = models.UUIDField(primary_key=True)
    insert_date = models.DateTimeField(auto_now_add=True)

and this is my serializer

class DeviceIdentifierSerializer(serializers.ModelSerializer):
    """
    Device identifier serializer
    """

    class Meta:
        model = DeviceIdentifier
        fields = ('id_device', 'owner')

and this is my view

class RegisterDevice(CreateAPIView):
    """
    View for registering device for the logged user
    """
    serializer_class = DeviceIdentifierSerializer

    def post(self, request, *args, **kwargs):
        obj = DeviceIdentifierSerializer(data=request.data)
        obj.is_valid()
        obj.save(owner=request.user)

        return Response(True)
WisdomPill
  • 720
  • 4
  • 11
  • 25

1 Answers1

0

Add Unique constaint on models instead of Model Serializer, it will surely work.

class DeviceIdentifier(models.Model):
    owner = models.ForeignKey(HDSAuthUser, on_delete=models.CASCADE)
    id_device = models.UUIDField(primary_key=True)
    insert_date = models.DateTimeField(auto_now_add=True)

      class Meta:
          unique_together = ('field1', 'field2',)

class DeviceIdentifierSerializer(serializers.ModelSerializer):
    """
    Device identifier serializer
    """

    class Meta:
        model = DeviceIdentifier
Sagar
  • 1,115
  • 2
  • 11
  • 23