如何获取Django模型中字段的默认值?

时间:2021-09-09 19:35:33

I have a Django model with some fields that have default values specified. I am looking to grab the default value for one of these fields for us later on in my code. Is there an easy way to grab a particular field's default value from a model?

我有一个Django模型,其中一些字段具有指定的默认值。我希望稍后在我的代码中为我们获取其中一个字段的默认值。有没有一种简单的方法从模型中获取特定字段的默认值?

4 个解决方案

#1


15  

You can get the field like this:

你可以得到这样的字段:

myfield = MyModel._meta.get_field_by_name('field_name')

and the default is just an attribute of the field:

并且默认值只是该字段的属性:

myfield.default

#2


39  

TheModel._meta.get_field('the_field').get_default()

#3


11  

As of Django 1.9.x you may use:

从Django 1.9.x开始,您可以使用:

field = TheModel._meta.get_field('field_name')
default_value = field.get_default()

#4


0  

If you need the default values for more than one field (e.g. in some kind of reinitialization step) it may be worth to just instantiate a new temporary object of your model and use the field values from that object.

如果您需要多个字段的默认值(例如,在某种重新初始化步骤中),则可能需要实例化模型的新临时对象并使用该对象的字段值。

temp_obj = MyModel()
obj.field_1 = temp_obj.field_1 if cond_1 else 'foo'
...
obj.field_n = temp_obj.field_n if cond_n else 'bar'

Of course this is only worth it, if the temporary object can be constructed without further performance / dependency issues.

当然,如果可以构造临时对象而没有进一步的性能/依赖性问题,那么这是值得的。

#1


15  

You can get the field like this:

你可以得到这样的字段:

myfield = MyModel._meta.get_field_by_name('field_name')

and the default is just an attribute of the field:

并且默认值只是该字段的属性:

myfield.default

#2


39  

TheModel._meta.get_field('the_field').get_default()

#3


11  

As of Django 1.9.x you may use:

从Django 1.9.x开始,您可以使用:

field = TheModel._meta.get_field('field_name')
default_value = field.get_default()

#4


0  

If you need the default values for more than one field (e.g. in some kind of reinitialization step) it may be worth to just instantiate a new temporary object of your model and use the field values from that object.

如果您需要多个字段的默认值(例如,在某种重新初始化步骤中),则可能需要实例化模型的新临时对象并使用该对象的字段值。

temp_obj = MyModel()
obj.field_1 = temp_obj.field_1 if cond_1 else 'foo'
...
obj.field_n = temp_obj.field_n if cond_n else 'bar'

Of course this is only worth it, if the temporary object can be constructed without further performance / dependency issues.

当然,如果可以构造临时对象而没有进一步的性能/依赖性问题,那么这是值得的。