views:

132

answers:

1

Say I have a Django class something like this:

class Person(models.Model):
    name = models.CharField(max_length=50)
    # ...

How can I programatically obtain the max_length value for the name field?

+8  A: 

Person._meta.get_field('name').max_length will give you this value. But having to use _meta suggests this is something you shouldn't do in normal usage.

Edit: as Carl pointed out, this naming is misleading and it does seem quite acceptable to use it: http://www.b-list.org/weblog/2007/nov/04/working-models/

Ben James
Good answer, but disagree with the second comment. The underscore in front of _meta is misleading, IMO (and I've seen Django core devs agree; it's partly there just to avoid name clashes with model fields). Using _meta isn't a bad smell, it's a good one; it means you're being DRY and not making unwarranted assumptions.
Carl Meyer
Carl: Actually you do seem to agree with my comment, which was only observing the naming convention and the implication this would normally have. You are correct that it is misleading though: see http://www.b-list.org/weblog/2007/nov/04/working-models/ for example
Ben James
I've found this naming annoying in the past, because you can't access variables with underscores at the beginning in Django templates. We added a new property that pointed at _meta to get round that.
StephenPaulger