user4581250
user4581250

Reputation:

What is class meta in model?

Recently I am doing a function that need to customize max length of User model. Now I know that I have learned how to solve my requirement.

When I type this code, I can extend max_length:

User._meta.get_field('username').max_length = 100
User._meta.get_field('email').max_length = 100

I still can't understand what meta is. When I try to read Django document about meta model, I just know that I should how to use meta. I need more explanation that let me really understand the inner meaning about meta.

Model Meta relative link:

https://docs.djangoproject.com/en/1.7/ref/models/options/ https://docs.djangoproject.com/en/1.7/topics/db/models/#meta-options

Upvotes: 0

Views: 485

Answers (1)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52153

From docs:

Model metadata is “anything that’s not a field”, such as ordering options (ordering), database table name (db_table), or human-readable singular and plural names (verbose_name and verbose_name_plural). None are required, and adding class Meta to a model is completely optional.

Thus, Meta is just a container class responsible for holding metadata information attached to the model. It defines such things as available permissions, associated database table name, whether the model is abstract or not, singular and plural versions of the name etc.

For the available Meta options, you can take a look at here.


As for your question, I would definitely avoid changing max_length to some other value like that, as you know, max_length also creates a database constraint such as VARCHAR(64) which can't be automatically updated to a new value (100) by Django.

Thus, if you want to change max length, make sure you also update the size of the column in the corresponding table column in the database:

For MySQL:

ALTER TABLE auth_user MODIFY username VARCHAR(100);

For PostgreSQL:

ALTER TABLE auth_user ALTER COLUMN username TYPE VARCHAR(100);

Upvotes: 3

Related Questions