rest_framework framework entry (c)

ModelSerializer类

When you need to serialize classes closely related Django model definition, ModelSerializer class provides a shortcut that lets you automatically create a Serializer class field corresponds to the model field.

ModelSerializer Serializer classes and class differences:

  • It will automatically generate a set of fields for you according to the model.
  • It will automatically generate a sequence of validators.
  • It includes a simple default implementation .create()and .update().

example:

from rest_framework import serializers

class UserInfoSerializer(serializers.ModelSerializer):
    '''创建序列化器'''
    class Meta:
        model = Book
        fields = ('id', 'name', 'price')
        # 注册Book下面那些字段

By default, all models based on the fields are mapped to the corresponding serializer field.

Specify which fields to include in the

If you want to use only a subset of the default fields in the model serializer, you can use fields or exclude option is strongly recommended to use the fields property is explicitly set to be serialized all fields. In this way the possibility of inadvertent exposure data model changes can be reduced.

When fields when property is set to the special value, '__all__'indication fields used in the model.
example:

from rest_framework import serializers

class UserInfoSerializer(serializers.ModelSerializer):
    '''创建序列化器'''
    class Meta:
        model = Book
        fields = '__all__' 

exclude from the serializer attribute in the list of excluded field. For example, Book models have both a name and price fields, will result in only the last name be serialized.

from rest_framework import serializers

class UserInfoSerializer(serializers.ModelSerializer):
    '''创建序列化器'''
    class Meta:
        model = Book
        exclude= ('price',) 

Field specifies the sequence of (or override the default field added)

example:

from rest_framework import serializers

class UserInfoSerializer(serializers.ModelSerializer):
    url = serializers.CharField(source='get_absolute_url', read_only=True)
    groups = serializers.PrimaryKeyRelatedField(many=True)

    class Meta:
        model = Book

Specify read-only field

example:

from rest_framework import serializers

class UserInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ('id', 'name', 'price')
        read_only_fields = ('name',)

Behind read_only_fields is a list of field names or tuple.

Guess you like

Origin blog.csdn.net/dakengbi/article/details/91391381
Recommended