DRF-如果任何定义的字段为None,则引发Exception [英] DRF - Raise Exception if any defined field is None

查看:81
本文介绍了DRF-如果任何定义的字段为None,则引发Exception的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将模型序列化为 JSON 。然后将此 JSON 发送到一个 API

I need to serialize model to JSON. Then send this JSON to one API.

但是此 API 要求某些字段不是 None

But this API requires some fields to be not None.

我有这些字段的列表。在这种情况下,我们假设它只是 ['电话'] ,但可以更多。

I have a list of these fields. In this case, let's say it's just ['telephone'] but it can be much more.

class UserSerializer(serializers.ModelSerializer):
    telephone = serializers.CharField(source='userprofile.telephone')
    class Meta:
        model = User
        fields = ['first_name','last_name','telephone']

序列化:

>>> UserSerializer(user).data
>>> {'first_name':'Michael','last_name':'Jackson','telephone':None}

由于 API 需要某些字段,例如电话,因此我需要 UserSerializer raise ValidationError 时,必填字段为 None

Since API requires some fields like telephone, I want UserSerializer to raise ValidationError when the required field is None.

所以在这种情况下,我无法序列化用户,因为电话 None

So in this case I couldn't serialize user because telephone is None.

我尝试了很多事情,包括在<$ c $中添加 required = True c>电话,但没有任何效果。

I tried many things including adding required=True to the telephone but nothing works.

是否有一种方法可以验证序列化数据?请注意,我并不是在说反序列化

Is there a way to validate serialized data? Note that I'm not talking about deserialization.

推荐答案

为什么要验证



仅在反序列化过程 (输入是 dict 之类的对象),而您正在尝试 序列化程序 。对于 序列化 ,DRF假定给定对象是有效对象,因此不需要验证。


来源 DRF序列化器

Why validation not working?

The validation process undergoes only while Deserialization process (input is a dict like object) and you are trying a Serialization process. In the case of Serialization, DRF assumes the given object is a valid one and hence it doesn't require a validation.

Source DRF-serializers

方法1

使您的用户对象成为user_data( dict 对象),并将其传递给序列化程序并运行验证。

Method-1
Make your user object to a user_data (dict object) and pass it to the serializer and run the validation.

user = User.objects.get(id=1)
dict_user_data = {"first_name": user.first_name, "last_name": user.last_name, "telephone": user.userprofile.telephone}
user_serializer = UserSerializer(data=dict_user_data)
user_serializer.is_valid(True)
user_serializer.data



方法2

覆盖遇到的 to_representation() hod


Method-2
Override the to_representation() method

class UserSerializer(serializers.ModelSerializer):
    telephone = serializers.CharField(source='userprofile.telephone')

    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'telephone']

    def to_representation(self, instance):
        data = super().to_representation(instance)
        for field, value in data.items():
            if value is None:
                raise SomeExceptionHere({field: "can't be None"})
        return data

这篇关于DRF-如果任何定义的字段为None,则引发Exception的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆