在进行验证时,将提取字段添加到Django模型序列化程序

时间:2016-12-13 07:28:22

标签: python django validation serialization django-rest-framework

假设我有以下模型和modelSerializer:

models.py

class Approve(models.Model):
    process = models.IntegerField(verbose_name='Associated Process')
    content = models.CharField(max_length=300, verbose_name="Approval Content")

serializers.py

class ApproveSerializer(serializers.ModelSerializer):
    class Meta:
        model = Approve
        fields = ('id', 'process' ,'content')
    def validate(self, value):
        process = value['process']
        try:
            something_else = Something.objects.get(process)
        except Something.DoesNotExist:
            raise serializers.ValidationError('Invalid Process')
        return value

<小时/> 问题是我想验证serializers.py中的传入数据,而不是views.py。您可以注意到,为了进行验证检查,我查询了数据库 something_else

问题是我想在views.py中使用此对象 something_else ,而不是进行另一个数据库查询。我有什么方法可以使用序列化程序传递它,而不会在调用serializer.is_valid()方法时导致序列化程序验证错误。

<小时/> 任何建议都会受到欢迎,提前谢谢。

2 个答案:

答案 0 :(得分:0)

我不确定你的views.py看起来如何,但实质上,你需要在那里实例化序列化器:

def approve_view(request):
    if request.method == "POST":
        process = request.POST.get('value', None)
        something_else = Something.objects.filter(process=process).first()
        serializer = ApproveSerializer(something_else=something_else) # This is where you pass the something_else object. 
        if serializer.is_valid():
             # Your code for successful validation.
        else:
             # Your code for failed validation

现在您已将something_else传递到ApproveSerializer,您需要将其设置为属性:

class ApproveSerializer(serializers.ModelSerializer):
    def __init__(self, something_else=None):
        self.something_else = something_else

    class Meta:
        model = Approve
        fields = ('id', 'process' ,'content')

    def validate(self, value):
        process = value['process']
        if not self.something_else:
             raise serializers.ValidationError('Invalid Process')
    return value

答案 1 :(得分:0)

我找到了解决问题的方法。

<强> serializers.py

class ApproveSerializer(serializers.ModelSerializer):
    class Meta:
        model = Approve
        fields = ('id', 'process' ,'content')
    def validate(self, value):
        process = value['process']
        try:
            something_else = Something.objects.get(process)
            value['something_else'] = something_else
        except Something.DoesNotExist:
            raise serializers.ValidationError('Invalid Process')
        return value

<强> views.py 在调用serializer.save()方法之前,应该弹出已添加到序列化程序的值。

def post(self, request):
    serializer = ApproveSerializer(data=request.data)
    if serializer.is_valid():
        something_else = serializer.validated_data.pop('something_else')
        something_else.property = new_property
        something_else.save()
        serializer.save()
    else:
        # Error handling goes here serialzier.errors

不确定这是一个好习惯,但至少它现在适用于我。希望知道更好的解决方案。