How do I get the default value for a field in a Dj

2019-03-10 20:11发布

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?

4条回答
女痞
2楼-- · 2019-03-10 20:42

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
查看更多
戒情不戒烟
3楼-- · 2019-03-10 20:44

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.

查看更多
Juvenile、少年°
4楼-- · 2019-03-10 21:01

As of Django 1.9.x you may use:

field = TheModel._meta.get_field('field_name')
default_value = field.get_default()
查看更多
Melony?
5楼-- · 2019-03-10 21:06
TheModel._meta.get_field('the_field').get_default()
查看更多
登录 后发表回答