英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论