I have a serializer and i want to validate if atleast one is selected from the many to many fields . I have two ManyToMany fields in the objects which are levels and categories.
My serializer:
class WorkflowSerializer(serializers.ModelSerializer):
class Meta:
model = Workflow
fields = ('id', 'name', 'description', 'levels', 'categories')
read_only_fields = ['id']
depth = 2
def validate_categories(self,categories):
if len(categories)==0:
raise serializers.ValidationError("You haven't selected any category,Please select alteast one")
def validate_levels(self, levels):
for level in levels:
if len(level['permissions'])==0:
raise serializers.ValidationError("You haven't specified a permission for the level")
return levels
Rn now the validationjs are not working as it should.The data is getting saved even if none is selected in the Many to Many field
validate()
- can't check it right now, but from what I recall thevalidate_{field}
is not called at all if field is empty or None - alternatively you could try to override those fields and set them to not allow empty/null values. – mfrackowiak