gpt4 book ai didi

python - 当我想稍后填充数据时,django模型抛出IntegrityError : (1048, "Column ' xxx'不能为空”)

转载 作者:行者123 更新时间:2023-12-01 05:06:25 25 4
gpt4 key购买 nike

正如标题所述,我定义了一个模型,例如:

class Test(models.Model):
owner = models.ForeignKey(Member)
name = models.CharField(max_length=6
score = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(10)])
service = models.ForeignKey(Service)
feel = models.ForeignKey(feel)
....

如果我这样做

t, created = Test.objects.get_or_create(owner=member)

它会抛出 IntegrityError: (1048, "Column 'xxx' can not be null") 。但我只是想稍后填充数据。在 Model 字段中添加 null=True 是不好的,而 Model 字段确实需要 not null。我怎样才能实现我的目标?

最佳答案

您必须在内存中创建对象并填写数据,然后再尝试将其保存到数据库。就数据库而言,在填写所有内容之前,该行无效。

所以:

t = Test(owner=member) # Does not go to the database

#
# some other non-related code
#

# The you update your Test object with all of the fields and save
t.name = 34
t.score = 4
t.service = service # added separately
t.feel = feel # added separately
t.save()

关于python - 当我想稍后填充数据时,django模型抛出IntegrityError : (1048, "Column ' xxx'不能为空”),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24924599/

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