Django Validators in Serializer vs Constarints in Models

Viewed 213

I have searched about this extensively and have not found any substantial explanation for this - I have read the DRF documentation and also gone over the following SO links Django Model field validation vs DRF Serializer field validation, Django Model field validation vs DRF Serializer field validation.

I have a certain Model where I want to define a Constraint where two fields cannot be the same and need to be unique together. Django models provide the following way to do this

class Std(models.Model):
    std_cons = models.DecimalField(max_digits=11, decimal_places=4, null=True, blank=True)
    target_cons = models.DecimalField(max_digits=11, decimal_places=4, null=True, blank=True)
    key_item = models.BooleanField(default=False)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields = ['std_cons','target_cons'], name='unique_std_entry')
        ]

I can also achieve this in the serializers using the UniqueTogetherValidator

from rest_framework.validators import UniqueTogetherValidator

class StdSerializer(serializers.Serializer):
    class Meta:
        model = Std
        fields = '__all__'
        validators = [
            UniqueTogetherValidator(
                queryset=Std.objects.all(),
                fields=['std_cons', 'target_cons']
            )
        ]

Questions:

  1. Which method should be used when and why?
  2. What is the significance of both the methods?
  3. Should both be used? (maybe Model Level to take care of DjangoAdmin and Serializer to take care of HTTP calls)
0 Answers
Related