[英]Django Model Field default value not applied when creating object manually
Say my object has a DecimalField
with default set to 20
. 假设我的对象的
DecimalField
默认设置为20
。 When I create an object in python and don't specify a value for that DecimalField
, it's None
. 当我在python中创建对象并且未为该
DecimalField
指定值时,它为None
。
How to make sure that default value is applied every time I don't supply a value? 如何确保每次不提供值时都应用默认值?
class SomeModel(models.Model):
"""Demonstrate the flaw of the default value."""
dec_field = models.DecimalField(default=1, blank=True, null=True)
my_model = SomeModel()
my_model.save() # this is where I expect the dec_field to become Decimal('1.0')
# instead it's None
通过使用诸如South之类的迁移工具或删除表并重新同步,确保模型和数据库已同步。
The default should be set with what you have described, would need more info about your example. 默认值应使用您所描述的内容进行设置,将需要有关示例的更多信息。 But if you wanted to override, or set the default manually you could do the following;
但是,如果您想覆盖或手动设置默认值,则可以执行以下操作;
DEC_FIELD_DEFAULT = 20
class Example(models.Model):
dec_field = models.DecimalField(default=DEC_FIELD_DEFAULT)
def __init__(self, *args, **kwargs):
super(Example, self).__init__(self, *args, **kwargs)
self.dec_field = DEC_FIELD_DEFAULT
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.