File tree 1 file changed +19
-2
lines changed
1 file changed +19
-2
lines changed Original file line number Diff line number Diff line change 1
1
from django .core .exceptions import ImproperlyConfigured
2
+ from django .db import models
2
3
3
4
try :
4
5
from rest_framework import serializers
10
11
11
12
12
13
class ValidatedModelSerializer (serializers .ModelSerializer ):
14
+ exclude_validation = None
15
+
13
16
def validate (self , data ):
14
- instance = self .instance or self .Meta .model (** data )
15
- instance .full_clean ()
17
+ """Performs model validation on serialized data.
18
+
19
+ Allows to avoid having to duplicate
20
+ model validation logic in the REST API."""
21
+ instance = self .instance
22
+ # if instance is empty (eg: creation)
23
+ # simulate for validation purposes
24
+ if not instance :
25
+ Model = self .Meta .model
26
+ instance = Model ()
27
+ for key , value in data .items ():
28
+ # avoid direct assignment for m2m (not allowed)
29
+ if not isinstance (Model ._meta .get_field (key ), models .ManyToManyField ):
30
+ setattr (instance , key , value )
31
+ # perform model validation
32
+ instance .full_clean (exclude = self .exclude_validation )
16
33
return data
You can’t perform that action at this time.
0 commit comments