Using the Metaclass in Django

Can someone explain why the metaclass is used in the following example.

Example:

Class Employee (models.Model): name = models.ForeignKey(name) Gender = models.IntegerField() class Meta: ordering = ["Gender"] 

Thanks.

+7
python django django-models
source share
4 answers

Because the author / programmer wants to sort the results by the value of the Gender field.

+3
source share

Django models use the Meta class to contain additional model information that does not have to be contained in the model class itself. Note that this is not the same as the Python metaclass ; This is a completely different topic.

In this case, he organizes or sorts the queries for this model by the gender field

+25
source share

In this case, it defines the default field for ordering if you do not provide ORDER_BY in your request.

+3
source share

This is explained in the Django documentation for models.

 https://docs.djangoproject.com/en/dev/topics/db/models/ 

Give metadata to your model using the inner Meta class, for example:

 Class Employee (models.Model): .... class Meta: ordering = ["attribute-X"] 

Another useful option can be used in the Meta class - verbose_name.

0
source share

All Articles