4

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)
Nick ODell
  • 15,465
  • 3
  • 32
  • 66
dracarys
  • 1,071
  • 1
  • 15
  • 31
  • The `constraints` in the model's Meta are imposed/applied on the DB (most of the time) whereas in the DRF serializer it is not. – JPG Jun 08 '21 at 16:09
  • 1
    @JPG Yes I understand that but I cannot think of an application where the validator at the serializer level would be required. Would the validations at the model not be enough, usually? Can you provide a use case where the serializer validdators would be needed without the model constraints – dracarys Jun 08 '21 at 17:09

1 Answers1

0

If you plan on creating or updating a model instance without a serializer than those constraints can go unchecked if you don't have the constraints defined on the model.

merhoo
  • 589
  • 6
  • 18
  • Yes I understand that but I cannot think of an application where the validator at the serializer level would be required. Would the validations at the model not be enough, usually? Can you provide a use case where the serializer validators would be needed without the model constraints. The answer is almost the same as one of the comments on the question. Can you please update your answer if you can provide a use case where just constraint on model level would not be enough – dracarys Mar 24 '23 at 06:18
  • the purpose of the serializer is to validate input and format outputs of models, and the model instance defines business logic. Most but not all of the business logic will be enforced as a DB constraint. So if you wanted to have a constraint that doesn't create DB constraints, that only django is enforcing, then you can use a serializer, but 99% the time you want data consistency at the DB level because someone could add inconsistent data by interacting directly with the DB – merhoo Mar 28 '23 at 14:26
  • Yes I understand that but I cannot think of an application where the validator at the serializer level would be required. Would the validations at the model not be enough, usually? Can you provide a use case where the serializer validators would be needed without the model constraint – dracarys Apr 18 '23 at 11:05
  • you can have different validations for the same field depending on the context in which it is used. If you have a field that is required when creating a new object, but optional when updating an existing object, you'd need additional serializer validation. – merhoo Apr 18 '23 at 15:20
  • you can have an API endpoint that accepts data in a specific format, but the data does not map directly to a model field – merhoo Apr 18 '23 at 15:20
  • either way, your example should be defined on a model level if you want the db to enforce that constraint – merhoo Apr 18 '23 at 15:23