0
votes

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

1
I would move this code to the general validate() - can't check it right now, but from what I recall the validate_{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

1 Answers

0
votes

This worked:

  def validate(self, data):
        if len(self.initial_data['categories'])==0:
            raise serializers.ValidationError("category not selected")
        for level in self.initial_data['levels']:
            if len(level['permissions'])==0:
                raise serializers.ValidationError("No permission added for a level")
        return data