Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I programmatically obtain the max_length of a Django model field?

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?

like image 793
Mat Avatar asked Dec 01 '09 21:12

Mat


People also ask

Can we inherit model in Django?

You can't create a form or use any other Django features with it. If you inherit the models. Model version, your Employee class will have all the methods of a Django Model, and it will inherit the first_name field as a database field that can be used in a form.

What is PK and ID in Django?

pk is more independent from the actual primary key field i.e. you don't need to care whether the primary key field is called id or object_id or whatever. It also provides more consistency if you have models with different primary key fields. id is also a built-in function in Python, I prefer to use pk because of that.

What is PK in Django models?

pk is short for primary key, which is a unique identifier for each record in a database. Every Django model has a field which serves as its primary key, and whatever other name it has, it can also be referred to as "pk".


1 Answers

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/

Read more at Django Docs: https://docs.djangoproject.com/en/dev/ref/models/meta/#django.db.models.options.Options.get_field

like image 88
Ben James Avatar answered Sep 28 '22 07:09

Ben James