Question

How can you know if a value is the default value for a Model's property.

For example

class Alias(models.Model) :
  image = models.ImageField(upload_to='alias', default='/media/alias-default.png')

a = Alias.get("123")
# this doesn't work
if a.image == a.image.default :
  pass
# nor this
if a.image == Alias.image.default :
  pass

I tried digging in the docs, but didn't see anything.

Was it helpful?

Solution

The default in Django is not the same as SQL default - it's there merely for admin to auto-fill the form field on new object creation.

If you want to compare something to value defined as default you have to define it somewhere else (i.e. in settings.py). Like:

class MyModel(models.Model):
    ...
    my_field = models.IntegerField(default=settings.INT_DEFAULT)

The default value is stored in MyModel._meta._fields()[field_creation_index].default but be aware that this is digging in internals.

OTHER TIPS

You can't get it from the property itself, you have to go via the model options under model._meta.

a._meta.get_field_by_name('image')[0].get_default()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top