How do I get the default value for a field in a Django model?

后端 未结 5 1330
日久生厌
日久生厌 2021-02-02 07:09

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

相关标签:
5条回答
  • 2021-02-02 07:31
    TheModel._meta.get_field('the_field').get_default()
    
    0 讨论(0)
  • 2021-02-02 07:31

    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

    0 讨论(0)
  • 2021-02-02 07:36

    As of Django 1.9.x you may use:

    field = TheModel._meta.get_field('field_name')
    default_value = field.get_default()
    
    0 讨论(0)
  • 2021-02-02 07:39

    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
    
    0 讨论(0)
  • 2021-02-02 07:48

    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.

    0 讨论(0)
提交回复
热议问题