views:

159

answers:

2

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.

+2  A: 

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.

zgoda
Is _meta supported or might change going forward?
Paul Tarjan
Anything with name beginning with underscore should be considered internal. Anyway, it did not change between 1.0 and 1.1.
zgoda
If you want to use the internal attribute (_meta is quite stable for internal API), it's easier to read MyModel._meta.get_field('field_name').default rather than accessing by creation index.
Carl Meyer
Sure, I didn't even know such method exists for Meta. I always used fields() for iteration over the complete list of fields, never tried to access single field attributes. :)
zgoda
+2  A: 

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()
Daniel Roseman
Is that supported or might change going forward?
Paul Tarjan