0

i am confuse on which is best to validation in serializer or in model (inside models.py save method) in django?

Serializer code

def save(self, force_insert=False, force_update=False, using=None,update_fields=None):
   if self.x > self.y:
       raise BadRequest(details={'message':'x should be less than y.'})
   return super(xx, self).save()

or

Models code

def validate(self, attrs):
    if attrs['x'] > attrs['y']:
       raise BadRequest(details={'message':'x should be less than y.'})
    return attrs 

which is most best practical? and how we can achieved thick model and thin view?

1 Answers1

0

There is not a best method. Both methods are valid depending on your architecture.

I personally try to add any validation such as this one directly on the model. This way no matter where the data comes from, it will always get validated. For example you may wish to also apply this validation when using your django admin - if you used a serializer, the django admin request would go past this validation as it would ignore the serializer.

Working with multiple developers is also a consideration. One less familiar with the project developer may not make use of the serializer which has the validation.

Again it depends on the architecture, sometimes it makes sense to have the validation on the serializer or view. I would always consider adding it on the model first to prevent data corruption from anything hitting your model.

Here's more reading if you wish.

Sorin Burghiu
  • 715
  • 1
  • 7
  • 26