Search code examples
classdjango-modelsdjango-rest-frameworkdjango-viewsmetadata

What does "class Meta:" do in Django and Django REST Framework?


I am trying to figure out what class Meta: really do in Django.

I come across with the code below in DRF, but not sure why under class Meta: there is model = User and fields = [...]. Does it help to create a database?

from django.contrib.auth.models import User, Group
from rest_framework import serializers


class UserSerializer(
        serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ['url', 'username', 'email', 'groups']

And also what is the different with the class Meta: used in Django as below.

from django.db import models

class Ox(models.Model):
    horn_length = models.IntegerField()

    class Meta:
        ordering = ["horn_length"]
        verbose_name_plural = "oxen"

I have tried to get further understanding from both Django and DRF documentation however I did not see the explanation for model = ... and fields = [...] used in DRF class Meta.


Solution

  • The concept of Meta class comes from metaprogramming. The term metaprogramming refers to manipulating itself. Python supports a form of metaprogramming for classes called metaclasses. Meta class is mainly the inner class of your main class. Meta class is basically used to change the behavior of your main class attributes. It’s completely optional to add a Meta class to your Class. But in your Django project, you have already seen this metaclass concept available in different places like models.py, serializers.py, admin.py, etc.

    Actually, this Meta class changes the common behavior of its main class like the model metaclass changing behavior using verbose_name, db_table, proxy, permissions, ordering etc, and a lot of other options. Meta class in serializer also does the exact same things it tells it the model to use and what fields to serialize by using fields, exclude, and model.