If we want to use the Serializer corresponding to Django's model class, DRF provides us with the ModelSerializer model class Serializer to help us quickly create a Serializer class.
ModelSerializer is the same as regular Serializer, but provides:
- Automatically generate a series of fields based on model class
- Contains the implementation of the default create() and update()
1. definition
Let's create a BookInfoSerializer
class BookInfoSerializer(serializers.ModelSerializer): """Book data serializer""" class Meta: model = BookInfo fields = '__all__'
- Model indicates which model class to reference
- Fields indicates which fields are generated for the model class
We can view the specific implementation of the automatically generated BookInfoSerializer in the python management.py shell
>>> from booktest.serializers import BookInfoSerializer >>> serializer = BookInfoSerializer() >>> serializer BookInfoSerializer(): id = IntegerField(label='ID', read_only=True) btitle = CharField(label='Name', max_length=20) bpub_date = DateField(allow_null=True, label='Release date', required=False) bread = IntegerField(label='Reading volume', max_value=2147483647, min_value=-2147483648, required=False) bcomment = IntegerField(label='Comment quantity', max_value=2147483647, min_value=-2147483648, required=False) image = ImageField(allow_null=True, label='picture', max_length=100, required=False)
2. Specify fields
1) use fields to specify the fields. The table name contains all fields, and you can also specify which fields, such as
class BookInfoSerializer(serializers.ModelSerializer): """Book data serializer""" class Meta: model = BookInfo fields = ('id', 'btitle', 'bpub_date')
2) which fields can be excluded by using exclude
class BookInfoSerializer(serializers.ModelSerializer): """Book data serializer""" class Meta: model = BookInfo exclude = ('image',)
3) the default ModelSerializer uses the primary key as the associated field, but we can use depth to simply generate a nested representation. Depth should be an integer, indicating the number of nested levels. Such as:
class HeroInfoSerializer2(serializers.ModelSerializer): class Meta: model = HeroInfo fields = '__all__' depth = 1
The serializer formed is as follows:
HeroInfoSerializer(): id = IntegerField(label='ID', read_only=True) hname = CharField(label='Name', max_length=20) hgender = ChoiceField(choices=((0, 'male'), (1, 'female')), label='Gender', required=False, validators=[<django.core.valators.MinValueValidator object>, <django.core.validators.MaxValueValidator object>]) hcomment = CharField(allow_null=True, label='Descriptive information', max_length=200, required=False) hbook = NestedSerializer(read_only=True): id = IntegerField(label='ID', read_only=True) btitle = CharField(label='Name', max_length=20) bpub_date = DateField(allow_null=True, label='Release date', required=False) bread = IntegerField(label='Reading volume', max_value=2147483647, min_value=-2147483648, required=False) bcomment = IntegerField(label='Comment quantity', max_value=2147483647, min_value=-2147483648, required=False) image = ImageField(allow_null=True, label='picture', max_length=100, required=False)
4) display the indicated fields, such as:
class HeroInfoSerializer(serializers.ModelSerializer): hbook = BookInfoSerializer() class Meta: model = HeroInfo fields = ('id', 'hname', 'hgender', 'hcomment', 'hbook')
5) indicate read-only field
Read only fields can be indicated by read only fields, i.e. only fields used to serialize output
class BookInfoSerializer(serializers.ModelSerializer): """Book data serializer""" class Meta: model = BookInfo fields = ('id', 'btitle', 'bpub_date', 'bread', 'bcomment') read_only_fields = ('id', 'bread', 'bcomment')
3. Add additional parameters
We can add or modify the original option parameters for ModelSerializer by using the extra﹐kwargs parameter
class BookInfoSerializer(serializers.ModelSerializer): """Book data serializer""" class Meta: model = BookInfo fields = ('id', 'btitle', 'bpub_date', 'bread', 'bcomment') extra_kwargs = { 'bread': {'min_value': 0, 'required': True}, 'bcomment': {'min_value': 0, 'required': True}, } # BookInfoSerializer(): # id = IntegerField(label='ID', read_only=True) # btitle = CharField(label = name ', max_length=20) # Bpub? Date = DateField (allow? Null = true, label = release date ', required=False) # bread = IntegerField(label = reading amount ', max_value=2147483647, min_value=0, required=True) # bcomment = IntegerField(label = comment amount ', max_value=2147483647, min_value=0, required=True)