如何更新字段以设置默认值?

huangapple go评论106阅读模式
英文:

How would I update a field to set a default value?

问题

在将现有的Django字段更新为具有默认值后,如果我将该字段保存为null值,我会收到错误消息:IntegrityError:列中的null值。而不是将字段设置为默认值,有人知道这可能是为什么吗?如果我包括null=True,它只会将其设置为null。

英文:

After updating an existing django field to have a default value if I save the field with a null value I get the error: IntegrityError: null value in column

rather than the field being set to the default, does anyone know why this may be? If I include null=True it just sets it to null.

答案1

得分: 1

class YourModel(models.Model):
your_given_field = models.CharField(max_length=100, default='default_value')

def save(self, *args, **kwargs):
if not self.your_given_field:
self.your_given_field = 'default_value'
super().save(*args, **kwargs)

英文:
class YourModel(models.Model):
      your_given_field = models.CharField(max_length=100, default='default_value')

def save(self, *args, **kwargs):
    if not self.your_given_field:
        self.your_given_field = 'default_value'
    super().save(*args, **kwargs)

答案2

得分: 0

我认为,通过明确尝试将字段保存为null,你正在覆盖默认值。只有在变量存在时才尝试更新对象。

my_variable = None

if my_variable:
    my_object.my_field = my_variable

如果您发布更多的代码,我可以提供更多帮助。

英文:

I think by explicitly trying to save the field as null you are overriding the default value. Try and update the object only if the variable exists.

my_variable = None

if my_variable:
    my_object.my_field = my_variable

if you post more of your code i could help more

huangapple
  • 本文由 发表于 2023年3月8日 18:11:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75671709.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定