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?

2 Answers 2

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.'
)
Sign up to request clarification or add additional context in comments.

1 Comment

how to change non_field_errors key to specific one?
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()

2 Comments

interesting way of doing it. is there a way of doing this without touching the actual model?
I believe the serializer has a save API as well. You may be able to do your wrappering there.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.