Skip to content

Commit f718456

Browse files
committed
[feature] Allow excluding fields from validation in ValidatedModelSerializer
Also handled exclusion of direct setting of m2m fields.
1 parent cb0a85a commit f718456

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

openwisp_utils/api/serializers.py

+19-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
from django.core.exceptions import ImproperlyConfigured
2+
from django.db import models
23

34
try:
45
from rest_framework import serializers
@@ -10,7 +11,23 @@
1011

1112

1213
class ValidatedModelSerializer(serializers.ModelSerializer):
14+
exclude_validation = None
15+
1316
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)
1633
return data

0 commit comments

Comments
 (0)