1

I have looked at this question but that doesn't really tell me about non-field errors.

My Model is:

class DeviceContact(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    contact_sid = models.CharField(max_length=75, db_index=True)
    contact_name = models.CharField(max_length=200)
    contact_email = models.CharField(max_length=250, db_index=True)
    contact_type = models.CharField(max_length=200, default='mobile')

    class Meta:
        unique_together = ("contact_sid", "contact_email", "contact_name")


class DeviceContactSerializer(serializers.ModelSerializer):
    class Meta:
        model = DeviceContact
        fields = ('contact_sid', 'contact_name', 'contact_email', 'contact_type')

How do I return a custom error message when the unique_together condition fails?

Community
  • 1
  • 1
blue_zinc
  • 2,410
  • 4
  • 30
  • 38

2 Answers2

2

When you have unique_together set on a model, the serializer will automatically generate a UniqueTogetherValidator that is used to check their uniqueness. You can confirm this by looking at the output of the serializer, and introspecting what Django REST framework automatically generates:

print(repr(DeviceContractSerializer()))

You can then alter the validators that are set to include your custom UniqueTogetherValidator with a custom message argument set up.

UniqueTogetherValidator(
    queryset=DeviceContract.objects.all(),
    fields=('contact_sid', 'contact_email', 'contact_name', ),
    message='This was not a unique combination within the system, pick a different one.'
)
Kevin Brown-Silva
  • 40,873
  • 40
  • 203
  • 237
1

How about overriding the DeviceContact's save method, intercepting the exception, and then re-throwing it to your liking?

class MySuperDuperException(Exception):
    pass

class DeviceContact(models.Model):
    [...]

    def save(self, *args, **kwargs):
        try:
            super(DeviceContact,self).save(*args,**kwargs)
        catch DeviceContact.IntegrityError as e:
            throw MySuperDuperException()
Ross Rogers
  • 23,523
  • 27
  • 108
  • 164