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.

Hope someone could help to explain the functioning principle behind. Thanks!

To fully understand the functioning of the inner Meta class, you need to understand how Python classes and Python metaclass programming work.

Django model classes are not created directly from the class definitions. Those definitions form a prototype for the real model class. It is the metaclasses that use those prototypes to create the actual class definitions during the initialization process, and the Meta class is the mechanism that Django uses to parameterize or modify the class creation process.

1 Like