Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of the class meta in Django?

For what purpose is the class Meta: used in the class inside the Django serializers.py file?

like image 333
Brijesh Kalkani Avatar asked Mar 03 '20 05:03

Brijesh Kalkani


People also ask

What is the use of Meta class?

A metaclass in Python is a class of a class that defines how a class behaves. A class is itself an instance of a metaclass. A class in Python defines how the instance of the class will behave. In order to understand metaclasses well, one needs to have prior experience working with Python classes.

What is class Meta in Django serializer?

What is class Meta in Django serializer? It serves the same point as using a Meta class object inside a Django model class, or a form class, etc. It's a standard pattern to attach configuration (metadata) to a set of fields that make up the model, form, or in this case, serializer.03-Mar-2020.

What is class meta abstract true in Django?

What are abstract base classes, definition by Django: “Abstract base classes are useful when you want to put some common information into a number of other models. You write your base class and put abstract=True in the Meta class. This model will then not be used to create any database table.

What is Meta class order?

Ordering is basically is used to change the order of your model fields. Order by your_field ascending ordering = ['your_field'] Order by your_field descending ordering = ['-your_field']


1 Answers

Serializer classes can also include reusable validators that are applied to the complete set of field data. These validators are included by declaring them on an inner Meta class.
Also when you are defining a serializer then meta tags will help the serializer to bind that object in the specified format

Below are some of the examples :

While validating request data in specified format:

class EventSerializer(serializers.Serializer):
    name = serializers.CharField()
    room_number = serializers.IntegerField(choices=[101, 102, 103, 201])
    date = serializers.DateField()

    class Meta:
        # Each room only has one event per day.
        validators = UniqueTogetherValidator(
            queryset=Event.objects.all(),
            fields=['room_number', 'date']
        )

While getting data from db

class AccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = Account
        fields = ['id', 'account_name', 'users', 'created']

More you can read here

like image 65
abhikumar22 Avatar answered Oct 01 '22 02:10

abhikumar22