Search code examples
pythondjangodjango-modelsdjango-rest-frameworkunique

unique_together in a model.Models vs uniquetogethervalidator of serializers


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 ?


Solution

  • 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.