models.py
class Book(models.Model):bid = models.AutoField(primary_key=True)name = models.CharField(max_length=32)price = models.DecimalField(max_digits=5, decimal_places=2)publish = models.ForeignKey(to='Publish', on_delete=models.CASCADE)authors = models.ManyToManyField(to='Author')def __str__(self):return self.name
ModelSerializer序列化器
class BookSerializer(serializers.ModelSerializer):class Meta:model = models.Book # 此处设置ModelSerializer所关联的表# 此处有俩种设置方法fields = '__all__' #方法1使用__all__会自动匹配models中的所有字段fields = ['bid', 'name', 'price', 'publish', 'authors', 'publish_read', 'authors_read'] #方法2使用列表的形式将需要对应的字段填入extra_kwargs = {'bid': {'read_only':True},'publish': {'write_only': True},'authors': {'write_only': True},} # 对自动对应的字段进行Serializer进行参数设置,此时的Serializer字段名与models中一致
