Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - How to get the max_length of a field

How do I access the max_length of a model field in Django? I am writing a serializer with the REST framework and I want to write a custom validation function to validate the length. Note that i am using SQLite, so the database itself does not enforce the max_length.

like image 484
b_pcakes Avatar asked Feb 19 '16 05:02

b_pcakes


1 Answers

You can use the Model _meta API for accessing details of your model's fields.

Here's an example:

class MyModel(models.Model):
    title = models.CharField(max_length=200)

# retrieve the max_length
MyModel._meta.get_field('title').max_length

The _meta became a formal API in Django version 1.8. The documentation can be found at https://docs.djangoproject.com/en/stable/ref/models/meta/

like image 56
Derek Kwok Avatar answered Sep 29 '22 16:09

Derek Kwok