Menu Close

Meta class in Django Model

Meta class in Django Model

Hi Django Developers, I hope you are doing well. In this article, I am going to explain to you all about meta class in Django models along with proper examples. If you are a Django beginner developer or intermediate, then definitely you may hear about meta class and meta options in Django.

If you have already knowledge about Django meta class and meta options Then you can skip it other stay tuned to this amazing guide because I am going to explain all about the Django meta class models.

What is Django?

Django is one of the most popular high-level Python web frameworks developed by experienced developers. Django takes care of the most of hassle of the web development itself, It lets you just focus and write your code. It is an open-source framework which means you don’t need to pay anything to use Django.

What are Django models?

Models in Django is one of the most important components of Django. Django models are just Python classes that subclass of django.db.models.Model class. Each Django models represent the single database table in the database.

Click Here to learn all about Django models.

This is a simple example of the Django model.

Example: Django Model


class People(models.Model):
    first_name = models.CharField(max_length=40, db_column="first_name", verbose_name="First Name")
    last_name = models.CharField(max_length=20, db_column="last_name", verbose_name="Last Name")
    gender = models.CharField(max_length=10, verbose_name="Gender", choices=gender_choice)
    age = models.IntegerField(db_column="age")

    def __str__(self):
        return f"{self.first_name} {self.last_name}"

Meta class in Django

Meta class is also a Python class that defines inside the Django model. It is the way to change the behavior of Django tables like table name, field order, field constraints, indexes, etc.

For example, You can see below the Django model along with the Django meta class and meta option.

Note:- It’s not mandatory to add meta class in Django models. It all depends on you.

How to define meta class in Django

To define a Django Meta class in the model, You have just made a class Meta inside your Django model and use all the meta options inside that Meta class.

For example, you can see the below example.

Example:


class People(models.Model):
    first_name = models.CharField(max_length=40, db_column="first_name", verbose_name="First Name")
    last_name = models.CharField(max_length=20, db_column="last_name", verbose_name="Last Name")
    gender = models.CharField(max_length=10, verbose_name="Gender", choices=gender_choice)
    age = models.IntegerField(db_column="age")

    def __str__(self):
        return f"{self.first_name} {self.last_name}"

    class Meta:
        ordering = ["age"]

Meta Options in Django

Django Meta class has a lot of meta options that you can give to your Django model to change the behavior of the Django model.

These are Django meta options that will be used in the Django meta class to change the behavior of the Django model.

abstract

If abstract = True in your Django model, This model will be an abstract base class for the other models.

abstract base class:- Abstract base class is a kind of Django model which common to all the models inherited from it. When you want to put some common information for the number of Django models, Then you can create an abstract base class by putting abstract = True in your Django Meta class.

app_label

If a model defines outside of an application in INSTALLED_APPS, it must be define which app it belongs to.

app_lebel = "app_name"

db_table

This Django meta option is used to assign the name of the table inside the database. For example, If I want to give the name of the following table as an employee, Then I will use the db_table option inside the Django Meta class.

Example:


class EmployeesTable(models.Model):
    first_name = models.CharField(max_length=40, db_column="first_name", verbose_name="First Name")
    last_name = models.CharField(max_length=20, db_column="last_name", verbose_name="Last Name")
    age = models.IntegerField(db_column="age")
	designation = models.CharField(max_length=100, db_column="employee designation")

    def __str__(self):
        return f"{self.first_name} {self.last_name}"

    class Meta:
        db_table = "employee"

ordering

This option is used to define the default ordering of the Django model QuerySet.It can be a tuple, list, or any expression.
For example, we have a model BlogPost.


class BlogPost(models.Model):
    post_title = models.CharField(max_length=100, db_column="post_title", verbose_name="Post Title")
    post_description = models.TextField(max_length=200, db_column="post_description", verbose_name="Post Description")
    post_body = models.TextField(max_length=2000, db_column="post_body", verbose_name="Post Body")
	post_length = models.IntegerField(db_column="content length")
    status = models.CharField(max_length=10, verbose_name="Blog Post Status", choices=choice)

For each string inside the list, a tuple represents the field name of the model. By default, the ordering meta option sort the result in ascending order, To sort the result in descending order, you have to use the prefix “” before the field name.

For example, To order by post_title in ascending order, use the below statement.

ordering = ["post_title"]

To order by post_title in descending order, Use this.

ordering = ["-post_title"]

Or it may be you want to order by post_title in ascending order and post_length in descending order, Then you can use this.

ordering = ["post_title", "-post_length"]

proxy

In the Django meta option, the proxy meta option is used to make Django model proxy model for another model by defining the proxy = True inside the Django Meta class.
For example, I have created two models that MyPerson treats as proxy models for the Person model.

Example


class Person(models.Model):
    name = models.CharField(db_column='person name', max_length=50)
    age = models.IntegerField(db_column="person's age", max_length=20)


class MyPerson(models.Manager):
    class Meta:
        proxy = True

indexes

A list of indexes that you want to define in your model. Each item inside a list represents the individual index.

Example:


class Person(models.Model):
    name = models.CharField(db_column='person name', max_length=50)
    age = models.IntegerField(db_column="person's age", max_length=20)
    email = models.EmailField(db_column="person's email", max_length=100)


    class Meta:
        indexes = [
            models.Index(fields=['name']),
            models.Index(fields=['email'], name='email_index')
        ]

unique_together

unique_together meta option in Django Meta class is the process that defines the set of fields that would be unique When they will combine together. Basically, it is used in the Django admin panel and it is enforced at the database level.

For example, I have created a Django model Person, where I want to name and age unique when they meet together.


class Person(models.Model):
    name = models.CharField(db_column='person name', max_length=50)
    age = models.IntegerField(db_column="person's age", max_length=20)
    email = models.EmailField(db_column="person's email", max_length=100)

    class Meta:
        unique_together = [["name", "age"]]

index_together

index_together meta option is a way of defining the set of fields that will be treated index together.


class Person(models.Model):
    name = models.CharField(db_column='person name', max_length=50)
    age = models.IntegerField(db_column="person's age", max_length=20)
    email = models.EmailField(db_column="person's email", max_length=100)

    class Meta:
        index_together = [["name", "age"]]

In the above Person Django model, name and age will treat the index together.

constraints

constraints are the process of applying rules in Django model fields. It is one of the most important concepts in the Django model. constraints meta option takes a list of constraints. Django provides various kinds of constraints that you can apply based on your need.

For example, I have a Django model called Voter and I don’t want to insert voter records whose age is less than 18.


class Voter(models.Model):
    voter_name = models.CharField(db_column='person name', max_length=50)
    voter_age = models.IntegerField(db_column="person's age", max_length=20)
    voter_email = models.EmailField(db_column="person's email", max_length=100)

    class Meta:
        constraints = [
            models.CheckConstraint(check=models.Q(voter_age__gt = 18), name="voter_age__gt_18")
        ]

In the above Django model, When you will try to insert new records whose voter_age is less than 18, Then it will raise an IntegrityError exception as you can see below.


>>> first_voter = Voter.objects.create(voter_name="Vishvajit", voter_age=12, voter_email='[email protected]') 
Traceback (most recent call last):
  File "C:\Users\Vishvajit Rao\OneDrive\Desktop\Django project\venv\lib\site-packages\django\db\backends\utils.py", line 89, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\Vishvajit Rao\OneDrive\Desktop\Django project\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 357, in execute
    return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: CHECK constraint failed: voter_age__gt_18

verbose_name

This meta option is used to assign the human-readable name of the Django objects.

verbose_name = "person"

If it is not given Django will use a munged version of the class name.StudentTable becomes student table.

verbose_plural_name

This Django meta option is used to define the plural name of the Django object.

verbose_plural_name = "persons"

If it is not given, Django will automatically use verbose_name + “s”.

Conclusion

Well, In this article we have successfully covered all about meta class in Django with the help of the proper example.

You have to remember one thing always, the Meta option is always used inside the Meta class. Meta class is the process of changing the behavior of Django models.

You can any meta options according to your requirements. I hope this article will be helpful for you, if you like this article, please share and keep visiting for Django tutorials.

Reference:- Django Meta options documentation

Thanks for your valuable timeā€¦

Best Django Tutorial for Beginners
How to use Abstract Model in Django

Related Posts