0

If i have a model A with (field1 and field2 are fields of model)

`unique_together = ('field1', 'field2')`

in Meta class and a serializer which is a model serializer on model A, then why should I or why should not I use Uniquetogethervalidator in Meta of serializer. Why we need this validator if we already have condition in Model? Or what is difference between using a unique_constraint in model and uniquetogethervalidator in serializer ?

1 Answer 1

2

Why we need this validator if we already have condition in Model?

To keep all of your validations on the serializer without needing to go into the model layer; in order to avoid doing partitioned validation so to speak.

DRF validation follows a different idea than that of Django's -- Django tries to do some validation on form level and delegate the rest to the model (e.g. unique_together) whereas DRF tries to consolidate all validations at the serializer level.

what is difference between using a unique_constraint in model and uniquetogethervalidator in serializer?

The UniqueTogether validator in DRF is implemented in the serializer i.e. before passing the data onto the next level (which is model). Also this validator is implemented in pure Python, that's why the queryset argument is mandatory for UniqueTogether to check out the uniqueness of the fields in there.

OTOH, unique_together in model implements a database constraint which is only checked while saving an object on DB and this checking is done/enforced by the DB itself.

Also, if you have unique_together constraints on the model and if you're using DRF ModelSerializer, then those constraints are converted to a UniqueTogetherValidator object by DRF so that it can do the validations before passing the data to DB.

2
  • Ok thanks. I got the point. But since i found a bug in uniquetogether validator github.com/encode/django-rest-framework/issues/7003 but i immediately want to use this uniquetogether validation in a modelserializer, so can i get the same result (or basically same validation error if this uniqueness is not met) if i dont use validator on serializer but only use constraint in model? Or it will give some different error? Commented Nov 23, 2019 at 4:21
  • @anveshagarwal The issue you referred actually contains two different things and will incur further discussion. To answer your very question regarding model's unique_together, the database will spit out the error for any violation and remember you can only use the fields that are defined on the model (you'd get the same error as in your first example of the issue for any field name that is not present).
    – heemayl
    Commented Nov 23, 2019 at 10:27

Your Answer

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

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