53

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mikec
  • 3,543
  • 7
  • 30
  • 34

5 Answers5

87
TheModel._meta.get_field('the_field').get_default()
Collin Anderson
  • 14,787
  • 6
  • 68
  • 57
  • 2
    This is the best answer. `.get_default()` is much more reliable, whereas `.default` does not always return the default (e.g. it might be `NOT_PROVIDED`). – Rufflewind Dec 25 '19 at 07:02
26

As of Django 1.9.x you may use:

field = TheModel._meta.get_field('field_name')
default_value = field.get_default()
Alex Panov
  • 758
  • 10
  • 11
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
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Anything with a _ is digging into the internals. See my question : http://stackoverflow.com/questions/1011946/django-know-if-property-is-the-default-value – Paul Tarjan Sep 12 '09 at 05:54
  • 10
    Nowadays the `get_field_by_name` method returns a tuple with the field object as its first item. – Adam May 09 '14 at 10:27
  • @PaulTarjan you are right, but the `_meta` is one of those well-established, not-too-likely to change elements. The general consensus is that it is OK to access a model's `_meta` directly. – Krystian Cybulski Oct 14 '14 at 21:20
  • 4
    field.default might be a callable. Should use get_default() – Vajk Hermecz Jan 14 '15 at 17:19
  • 8
    Down voting because this is currently out of date. – fluffels Nov 11 '15 at 17:15
  • 7
    Down voted because it's currently out of date. Should do TheModel._meta.get_field('the_field').get_default() – TheMan Feb 21 '17 at 22:37
  • 1
    `.default` does not always return the default (e.g. it might be `NOT_PROVIDED`). `.get_default()` is much more reliable. – Rufflewind Dec 25 '19 at 07:01
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

Elisha
  • 4,811
  • 4
  • 30
  • 46
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
  • 2,199
  • 1
  • 12
  • 11