0

假设我的对象具有DecimalField默认设置为20. 当我在 python 中创建一个对象并且没有为它指定一个值时DecimalField,它是None.

如何确保每次我不提供值时都应用默认值?

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
4

2 回答 2

3

确保您的模型和数据库已同步,可以使用 South 等迁移工具,也可以删除表并重新同步。

于 2012-09-06T21:53:30.150 回答
1

默认值应设置为您所描述的内容,需要有关您的示例的更多信息。但是,如果您想覆盖或手动设置默认值,您可以执行以下操作;

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
于 2012-09-06T21:51:45.447 回答