tags:

views:

142

answers:

1

Is it possible to read a Django model's fields' options? For example, with the model:

class MyModel(models.Model):
    source_url = models.URLField(max_length=500)
    ...

i.e. how would I programmatically read the 'max_length' option from, say, within a view or form.

My current workaround is to define a separate class attribute:

class MyModel(models.Model):
    SOURCE_URL_MAX_LENGTH=500
    source_url = models.URLField(max_length=SOURCE_URL_MAX_LENGTH)
    ...

I can then access that from anywhere that imports models.MyModel, e.g.:

 from models import MyModel
 max_length = MyModel.SOURCE_URL_MAX_LENGTH
+5  A: 

Do it this way.

from models import MyModel
try:
    max_length = MyModel._meta.get_field('source_url').max_length
except:
    max_length = None
simplyharsh
Works well, thanks.
msanders