Goran
Goran

Reputation: 6824

django get default model field value

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()
    ...

Upvotes: 1

Views: 1458

Answers (2)

ThePhi
ThePhi

Reputation: 2611

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

Upvotes: 3

sebb
sebb

Reputation: 1966

myfield = Foo._meta.get_field_by_name('bar_field')

and the default is just an attribute of the field:

myfield.default

Upvotes: 0

Related Questions