pythondjangodjango-modelsmetadata

What is exactly Meta in Django?


I want know simply what is Meta class in Django and what they do.

from django.db import models

Class Author(models.Model):
    first_name=models.CharField(max_length=20)
    last_name=models.CharField(max_length=20)
    
    class Meta:
        ordering=['last_name','first_name']

Solution

  • Meta is a word that originates from the ancient Greeks and it means "meta is used to describe something that's self-reflective or self-referencing.". Specific to Django it is a class in which you describe certain aspects of your model. For example how the records should be ordered by default, what the name of the database table for that model is, etc.

    The documentation on meta options [Django-doc] says:

    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.

    The Django documentation contains an exhaustive list of Django's model Meta options. For example for the ordering attribute [Django-doc]:

    The default ordering for the object, for use when obtaining lists of objects. (...)

    Here the ordering specifies that if you query for Author objects, like Author.objects.all(), then Django will, if you do not specify any ordering, order the Authors by last_name first, and in case of a tie, order by first_name.