ModelSerializer serializer of DRF framework

ModelSerializer is a subclass of Serializer. Serialization and deserialization are the same as Serializer.

ModelSerializer is the same as a regular Serializer, but provides:

  • Automatically generate a series of fields based on model classes
  • Automatically generate validators for Serializer based on model classes, such as unique_together
  • Contains default implementations of create() and update()

When using the ModelSerializer serializer, we only need to define the serializer class and specify the corresponding model class and fields.

Example:

# Define ModelSerializers serializer
class BookInfoModelSerializer(serializers.ModelSerializer):
    '''Defines the ModelSerializers serializer for book information'''

    class Meta:
        #Specify the model class corresponding to the serializer
        # model = model class name
        model = BookInfo

        # Specify fields for serialization and deserialization operations
        fields = '__all__' # __all__ means all fields are serialized

Shell test code:

>>> from booktest.serializers import BookInfoModelSerializer
>>> s = BookInfoModelSerializer()
>>>s
BookInfoModelSerializer():
    id = IntegerField(label='ID', read_only=True)
    btitle = CharField(label='name', max_length=20)
    bpub_date = DateField(label='Published Date')
    bread = IntegerField(label='Reading volume', max_value=2147483647, min_value=-2147483648, required=False)
    bcomment = IntegerField(label='Comment volume', max_value=2147483647, min_value=-2147483648, required=False)
    is_delete = BooleanField(label='logical delete', required=False)

By testing the code, we can find that the ModelSerializer serializer automatically defines the field information and constraint information for us.

After experiencing the simplicity of the ModelSerializer serializer, we began to study it formally.

Note:

fields=’__all__’: Does not include foreign key fields. Foreign key fields are special fields and must be defined by yourself to achieve serialization.

1. Create ModelSerializer serializer class

1.1 Serialize and deserialize all fields in the model class.

We can specify the field data that the serializer can operate by setting the value of the fields attribute in the Meta class.
When fields=’__all__’, it means that the serializer can serialize and deserialize all field data in the model class.

# Define ModelSerializers serializer
class BookInfoModelSerializer(serializers.ModelSerializer):
    '''Defines the ModelSerializers serializer for book information'''

    class Meta:
        #Specify the model class corresponding to the serializer
        # model = model class name
        model = BookInfo

        # Perform serialization and deserialization operations on all fields
        fields = '__all__' # __all__ means all fields are serialized

Shell test code:

We can see the fields that can be serialized and deserialized through the Shell code, and we can find that the ModelSerializer serializer has automatically created the model fields and constraints for us.

>>> from booktest.serializers import BookInfoModelSerializer
>>> s = BookInfoModelSerializer()
>>>s
BookInfoModelSerializer():
    id = IntegerField(label='ID', read_only=True)
    btitle = CharField(label='name', max_length=20)
    bpub_date = DateField(label='Published Date')
    bread = IntegerField(label='Reading volume', max_value=2147483647, min_value=-2147483648, required=False)
    bcomment = IntegerField(label='Comment volume', max_value=2147483647, min_value=-2147483648, required=False)
    is_delete = BooleanField(label='logical delete', required=False)

1.2 Serialize and deserialize specific fields in the model class.

When fields = (‘Field 1’,…), it means that the current serializer can only process fields in tuple Perform serialization and deserialization operations.

class BookInfoModelSerializer(serializers.ModelSerializer):
    '''ModelSerializers serializer'''

    class Meta:
        #Specify the model class corresponding to the serializer
        model = BookInfo

        # Perform serialization and deserialization operations on the specified fields
        fields = ('bread','btitle','bcomment')

Shell test code:

>>> from booktest.serializers import BookInfoModelSerializer
>>> s = BookInfoModelSerializer()
>>>s
BookInfoModelSerializer():
    btitle = CharField(label='name', max_length=20)
    bread = IntegerField(label='Reading volume', max_value=2147483647, min_value=-2147483648, required=False)
    bcomment = IntegerField(label='Comment volume', max_value=2147483647, min_value=-2147483648, required=False)

1.3 Specify fields in the model class that cannot be serialized and deserialized.

In the Meta class, we can also set the field data that cannot be serialized and deserialized by the current serializer by specifying the value of the exclude attribute.

class BookInfoModelSerializer(serializers.ModelSerializer):
    '''ModelSerializers serializer'''

    class Meta:
        #Specify the model class corresponding to the serializer
        model = BookInfo

        #Specify fields that are not to be serialized and deserialized
        exclude = ('id', )

Shell test code:

>>> from booktest.serializers import BookInfoModelSerializer
>>> s = BookInfoModelSerializer()
>>>s
BookInfoModelSerializer():
    btitle = CharField(label='name', max_length=20)
    bpub_date = DateField(label='Published Date')
    bread = IntegerField(label='Reading volume', max_value=2147483647, min_value=-2147483648, required=False)
    bcomment = IntegerField(label='Comment volume', max_value=2147483647, min_value=-2147483648, required=False)
    is_delete = BooleanField(label='logical delete', required=False)

We can find that the field specified by the exclude attribute has not been created, which means that it cannot be operated by the serializer.

1.4 Specify related fields

Because the ModelSerializer serializer is a subclass of Serializer, the ModelSerializer serializer can also do what Serializer serialization can do.

In the ModelSerializer serializer, we also need to append associated fields to implement associated serialization operations, and the association method is consistent with the Serializer serializer.

Here, I will only give an example of many-to-one association, so that everyone can understand it.

class HeroInfoModelSerializer(serializers.ModelSerializer):
    '''Define the ModelSerializer serializer that queries Hero information'''

    #Add related fields (many to one)
    hbook = BookInfoModelSerializer()

    class Meta:
        #Specify model class
        model = HeroInfo
        #Specify fields
        fields = ('id', 'hname', 'hbook')

Shell test code:

>>> from booktest.serializers import HeroInfoModelSerializer
>>> s = HeroInfoModelSerializer()
>>>s
HeroInfoModelSerializer():
    id = IntegerField(label='ID', read_only=True)
    hname = CharField(label='name', max_length=20)
    hbook = BookInfoModelSerializer():
        id = IntegerField(label='ID', read_only=True)
        btitle = CharField(label='name', max_length=20)
        bpub_date = DateField(label='Published Date')
        bread = IntegerField(label='Reading volume', max_value=2147483647, min_value=-2147483648, required=False)
        bcomment = IntegerField(label='Comment volume', max_value=2147483647, min_value=-2147483648, required=False)
        is_delete = BooleanField(label='logical delete', required=False)

1.5 Specify read-only fields

In the ModelSerializer serializer, we can set read-only fields by specifying the value of the read_only_fields attribute in the Meta class.

class BookInfoModelSerializer(serializers.ModelSerializer):
    '''Defines the ModelSerializers serializer for book information'''

    class Meta:
        #Specify the model class corresponding to the serializer
        # model = model class name
        model = BookInfo

        # Perform serialization and deserialization operations on all fields
        fields = '__all__' # __all__ means all fields are serialized

        #Define read-only fields
        read_only_fields = ('id',)

Shell test code:

>>> from booktest.serializers import BookInfoModelSerializer
>>> s = BookInfoModelSerializer()
>>>s
BookInfoModelSerializer():
    id = IntegerField(label='ID', read_only=True)
    btitle = CharField(label='name', max_length=20)
    bpub_date = DateField(label='Published Date')
    bread = IntegerField(label='Reading volume', max_value=2147483647, min_value=-2147483648, required=False)
    bcomment = IntegerField(label='Comment volume', max_value=2147483647, min_value=-2147483648, required=False)
    is_delete = BooleanField(label='logical delete', required=False)

By testing the code, we can find that the id field is set with the read_only attribute.

1.6 Add validation parameters for specified fields

In the ModelSerializer serializer, we can add validation parameters for the specified fields by specifying the value of the extra_kwargs attribute in the Meta class.

Here, what we need to pay attention to is that the value format of the extra_kwargs attribute is a dictionary.

extra_kwargs = {
     'Field name':{
          'Verification options':'Verification conditions',
     }
}

Case Code:

class BookInfoModelSerializer(serializers.ModelSerializer):
    '''Defines the ModelSerializers serializer for book information'''

    class Meta:
        #Specify the model class corresponding to the serializer
        # model = model class name
        model = BookInfo

        # Perform serialization and deserialization operations on all fields
        fields = '__all__' # __all__ means all fields are serialized

        # Add field validation options
        extra_kwargs = {
            'bcomment':{
                'min_value':0,
                'max_value':99999
            }
        }

Shell test code:

>>> from booktest.serializers import BookInfoModelSerializer, HeroInfoModelSerializer
>>> s = BookInfoModelSerializer()
>>>s
BookInfoModelSerializer():
    id = IntegerField(label='ID', read_only=True)
    btitle = CharField(label='name', max_length=20)
    bpub_date = DateField(label='Published Date')
    bread = IntegerField(label='Reading volume', max_value=2147483647, min_value=-2147483648, required=False)
    bcomment = IntegerField(label='Comments', max_value=99999, min_value=0, required=False)
    is_delete = BooleanField(label='logical delete', required=False)

By testing the code, we can find that two new validation conditions have been set for the bcomment field.

2. Other operations of the ModelSerializer serializer

At the beginning of this article, I mentioned that ModelSerializer is a subclass of Serializer, so ModelSerializer can also perform extended verification operations.

I won’t go into details here. The method is the same as that of the Serializer. You only need to verify the method and override the method in the serializer class.

Here is the article about the Serializer serializer. You can refer to the verification of the Serializer serializer to perform custom verification for the ModelSerializer serializer.

Serializer: https://www.cnblogs.com/chao666/p/12269977.html