17👍
✅
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
- [Django]-What is the best approach to change primary keys in an existing Django app?
- [Django]-Populating django field with pre_save()?
- [Django]-How can I auto-populate a PDF form in Django/Python?
27👍
As of Django 1.9.x you may use:
field = TheModel._meta.get_field('field_name')
default_value = field.get_default()
- [Django]-Get user profile in django
- [Django]-Django: Where to put helper functions?
- [Django]-Django's ManyToMany Relationship with Additional Fields
2👍
if you don’t want to write the field name explicitly, you can also do this:
MyModel._meta.get_field(MyModel.field.field_name).default
- [Django]-TemplateDoesNotExist – Django Error
- [Django]-Django Order By Date, but have "None" at end?
- [Django]-How to disable Django's invalid HTTP_HOST error?
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.
👤ecp
- [Django]-How do I unit test django urls?
- [Django]-Django JSONField inside ArrayField
- [Django]-How do I create sub-applications in Django?
Source:stackexchange.com