DRF序列化之ModelSerializer

前面我们通过DRF的APIView方法实现了序列化、前面我们提到了几个非常重要的概念,比如Serializer序列化和APIView。既然Django为我们提供了Form和ModelForm,那么在DRF里面有没有类似的方法呢?有的、下面我们再一起看看DRF提供的另外一个序列化方法:ModelSerializer。

# 官方示例
class SnippetSerializer(serializers.ModelSerializer):
    class Meta:
        model = Snippet
        fields = ['id', 'title', 'code', 'linenos', 'language', 'style']


# 实际代码
from rest_framework import serializers
from .models import Goods


class GoodsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Goods
        fields = ('name', 'goods_sn', 'click_num', 'sold_num', 'fav_num', 'goods_num')

ModelSerializer让我们省去了字段的添加、使代码更加精简;我们可以把需要实现序列化的字段添加到fields里面去。但是有没有一个办法可以把所有字段一次性都拿到呢?

from rest_framework import serializers
from .models import Goods


class GoodsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Goods
        # fields = ('name', 'goods_sn', 'click_num', 'sold_num', 'fav_num', 'goods_num')
        fields = "__all__"

注:我们可以通过上面的all参数一次性把所有字段都取出来;ModelSerializer还会自动把外键字段的ID显示出来。

既然ModelSerializer可以把外键的ID拿到、那如果我们想获取到外键的完整信息呢?怎么办?ModelSerializer可以帮我们自动实现呢?答案是可以的。我们可以通过Serializer的嵌套来实现:

from rest_framework import serializers
from .models import Goods, GoodsCategory


class GoodsCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategory
        # fields = ('name', 'goods_sn', 'click_num', 'sold_num', 'fav_num', 'goods_num')
        fields = "__all__"


class GoodsSerializer(serializers.ModelSerializer):
    category = GoodsCategorySerializer()

    class Meta:
        model = Goods
        # fields = ('name', 'goods_sn', 'click_num', 'sold_num', 'fav_num', 'goods_num')
        fields = "__all__"

这里我们使用 category = GoodsCategorySerializer() 来覆盖默认的 category 外键字段。从下图我们可以看到、我们采用很简单的代码就实现了复杂的嵌套式序列化;这种能力是Django所不具备的。

推荐文章

4条评论

  1. I have read some excellent stuff here. Definitely worth bookmarking for revisiting. Roseann Claus Aeriela

  2. If you would like to get a great deal from this paragraph then you have to apply these methods to your won weblog. Marjie Elsworth Afton

  3. Fabulous, what a weblog it is! This website gives helpful information to us, keep it up. Hillary Derron Mungo

  4. You completed certain nice points there. I did a search on the matter and found mainly people will agree with your blog. Tressa Wait Zischke

发表评论

邮箱地址不会被公开。 必填项已用*标注