You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django REST framework中为ModelSerializer所有字段设置allow_null=True

批量为ModelSerializer所有字段设置allow_null=True的方案

Django REST Framework没有提供像read_only_fields那样直接批量配置allow_null=True的内置参数,但可以通过重写序列化器的方法实现批量设置,下面提供两种可行方案:

方法一:重写get_fields()方法

该方法会返回序列化器的所有字段,遍历这些字段并统一设置allow_null=True。如果你的自定义字段已经手动设置了allow_null,可以添加判断逻辑保留原有设置,避免被覆盖。

class ProductPublicListSerializer(serializers.ModelSerializer):
    minimum_price = serializers.FloatField(source='min_product_price', allow_null=True)
    maximum_price = serializers.FloatField(source='max_product_price', allow_null=True)

    def get_fields(self):
        fields = super().get_fields()
        for field in fields.values():
            # 如需保留自定义字段已有的allow_null设置,可取消下面的注释并调整判断逻辑
            # if not hasattr(field, 'allow_null') or field.allow_null is not True:
            field.allow_null = True
        return fields

    class Meta:
        model = Product
        fields = ('id', 'name', 'featured_image', 'minimum_price', 'maximum_price', 'total_review', 'average_rating')
        read_only_fields = ('name', 'featured_image', 'minimum_price', 'total_review')

方法二:重写create_field()方法

这个方法专门负责创建与模型字段对应的序列化字段,只会影响自动生成的模型字段,不会改动你手动定义的字段(除非自定义字段未设置allow_null,此时会被统一设为True)。

class ProductPublicListSerializer(serializers.ModelSerializer):
    minimum_price = serializers.FloatField(source='min_product_price', allow_null=True)
    maximum_price = serializers.FloatField(source='max_product_price', allow_null=True)

    def create_field(self, model_field, **kwargs):
        field = super().create_field(model_field, **kwargs)
        field.allow_null = True
        return field

    class Meta:
        model = Product
        fields = ('id', 'name', 'featured_image', 'minimum_price', 'maximum_price', 'total_review', 'average_rating')
        read_only_fields = ('name', 'featured_image', 'minimum_price', 'total_review')

内容的提问来源于stack exchange,提问作者Rafsan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 09:45:33