1

I want to write a view to reset some model field values to their default. How can I get default model field values?

class Foo(models.Model):
    bar_field = models.CharField(blank=True, default='bar')

so what I want is:

def reset(request, id):
    obj = get_object_or_404(Foo, id=id)
    obj.bar_field = # logic to get default from model field
    obj.save()
    ...
Goran
  • 6,644
  • 11
  • 34
  • 54

2 Answers2

3

Since Django 1.10: myfield = Foo._meta.get_field('bar_field').get_default()

see here (not explained in the Docs apparently...) : https://github.com/django/django/blob/master/django/db/models/fields/init.py#L2301

ThePhi
  • 2,373
  • 3
  • 28
  • 38
0
myfield = Foo._meta.get_field_by_name('bar_field')

and the default is just an attribute of the field:

myfield.default
sebb
  • 1,956
  • 1
  • 16
  • 28
  • Actually it's myfield = Foo._meta.get_field('bar_field') but you point me to the right direction. Thank you. – Goran Sep 20 '16 at 14:03
  • 1
    deprecated in Django 1.10: https://docs.djangoproject.com/en/1.11/ref/models/meta/#module-django.db.models.options – ThePhi Aug 25 '17 at 12:09