在将模型保存到数据库中之前尝试对其进行验证。使用POST api在特定模型中创建模型对象

时间:2019-12-29 09:47:37

标签: django django-models django-rest-framework

LocalizationDelegate

我试图实现一个合规性组可以属于一个合规性法律,但是可以从该法律中获得任何数量的合规性,但是到目前为止,它也可以从其他合规性法律中创建合规性组。

1 个答案:

答案 0 :(得分:0)

您可以尝试此代码

from rest_framework.exceptions import ValidationError

class ComplianceGroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = ComplianceGroup
        fields = (
            "id",
            "name",
            "compliance_law",
            "compliance",
            "created_on",
            "modified_on",
        )
        read_only_fields = ("created_on", "modified_on")
    def validate(self, attrs):
        compliance_law = attrs.get('compliance_law')
        compliance = attrs.get('compliance')
        # make your logic here 
        for comp in compliance:
            if comp.compliance_law != compliance_law:
                raise ValidationError({
                    'compliance': [_('All compliances should be part of compliance_law.')]
                })

        # or return attrs if every thing is ok as this method should return attrs or raise an error 
        return attrs