gpt4 book ai didi

python - Django (DRF) 序列化程序插入 NULL

转载 作者:行者123 更新时间:2023-11-30 21:46:09 26 4
gpt4 key购买 nike

我遇到了 Django 的问题,我试图在 MySQL 数据库中插入一个新行,而不为未指定的数据提供 NULL。

例如,考虑以下内容:

class MyModel(models.Model):
class Meta:
db_table = 'model_table'
managed = False

a = models.AutoField(primary_key=True)
b = models.CharField(max_length=255)
c = models.CharField(max_length=255, blank=True)

为 save() 向序列化程序提供以下数据时:

    data = list()
data['b'] = 'Some Text'
serializer = serializers.MyModelSerializer(data=data)
serializer.save()

对于每个未指定的字段,生成的结果 SQL 都为 NULL,在本例中为“c”。数据库中的表不允许 NULL,但有默认值来处理未指定的数据。

是否可以重写此序列化程序功能以允许在尝试插入时完全省略字段,或者我是否必须创建一个省略这些字段的新模型并为这种特定情况创建一个“创建”模型对这些领域有了解吗?

注意:Serializer 在其 fields 变量中只有字段“b”,因此它不会立即知道“c”列。

编辑:尝试澄清一点,这是生成的 SQL,由于列中不允许空值,它失败了。但是,“c”确实有默认值。

INSERT INTO `model_table` (`b`, `c`) VALUES ('Some Text', NULL)

PK 的 'a' 的 AutoField 没问题,这在默认情况下被省略,但 'c' 被替换为 NULL,因为在提供给序列化程序的数据中没有提供任何值,而不是从完全是SQL。作为一种解决方法,我复制了模型并从中删除了不需要的字段以使其正常工作,并且生成的 SQL 是有效的,因为模型本身不了解列,但这看起来不像最好的方法来做到这一点。以下是我希望此模型和序列化程序组合输出的内容

INSERT INTO `model_table` (`b`) VALUES ('Some Text')

这样 'c' 被提供为 MySQL 本身提供的默认列值。当我没有向序列化程序提供任何数据时,模型和序列化程序尝试插入 NULL 是问题所在。

最佳答案

您可以像下面这样重写序列化器创建方法

class UserSerializer(serializers.ModelSerializer):
profile = ProfileSerializer()

class Meta:
model = User
fields = ('username', 'email', 'profile')

def create(self, validated_data):
profile_data = validated_data.pop('profile')
user = User.objects.create(**validated_data)
Profile.objects.create(user=user, **profile_data)
return user

关于python - Django (DRF) 序列化程序插入 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49397352/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com