I have a question about writing reusable validation logic shared between 
the admin and DRF. If I have this setup: 

class Foo(models.Model): 
  from = models.IntegerField() 
  to = models.IntegerField() 
  def clean(self): if self.from > self.to: 
    raise ValidationError("`From` must be before or equal to `to`") 

class FooSerializer(serializers.ModelSerializer): 
  class Meta: 
    model = Foo 

Then starting with DRF3 the clean() validation will not be called by the 
serializer. The docs mention that I could use this mixin: 

def validate(self, attrs): 
  model = self.Meta.model 
  instance = Model(attrs) 
  instance.clean() 


but that it is dispreferred, and suggests "you really should look at 
properly separating the validation logic out of the model method if 
possible". How would I factor logic like the above so that it could be used 
in the admin and in DRF? What if the logic gets more complex, like "field B 
can be populated only if field A is > 7"?

Would I do something like this?  The reach into __dict__ feels weird.

def ordervalidator(dct):
   if self.from > self.to: 
      raise ValidationError # Using Django ValidationError, because the 
model admin needs it?

class Foo(models.Model): 
  from = models.IntegerField() 
  to = models.IntegerField() 
  validators = [ordervalidator]
  def clean(self): 
   for validator in self.validators:
      validator(self.__dict__)     

class FooSerializer(serializers.ModelSerializer): 
  class Meta: 
    model = Foo 
    validators = [ordervalidator]

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/4459f9cd-9d3f-494c-9de4-083d0d327efco%40googlegroups.com.

Reply via email to