django序列化程序多方字段验证

时间:2019-02-20 09:14:08

标签: python django django-rest-framework

我有一个序列化程序,我想验证是否从许多字段中选择了至少一个。我在对象中有两个ManyToMany字段,分别是级别和类别。

我的序列化器:

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现在validationjs无法正常工作。即使在“多对多”字段中未选择任何数据,数据也会被保存

1 个答案:

答案 0 :(得分:0)

这有效:

  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