码迷,mamicode.com
首页 > 其他好文 > 详细

Drf 序列化 ModelSerializer跨表取数据

时间:2019-11-05 18:43:02      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:lis   选择   tle   pytho   fun   clu   keyword   word   ring   

 

1、对于OneToOne、Foreignkey、choices字段可以使用source取出相关信息:

class CourseSerializer(serializers.ModelSerializer):
    # choices字段
    degree = serializers.CharField(source=‘get_degree_display‘)
    # ForeignKey字段
    teacher = serializers.CharField(source=‘teacher.name‘)
    class Meta:
        model = Course
        fields = ‘__all__‘

2、对于ManyToMany字段,例如:

class BookSerializers(serializers.ModelSerializer):
    authors  = serializers.SerializerMethodField()
    publisher = serializers.CharField(source=‘publisher.title‘)
    class Meta:
        model = Book
        fields = "__all__"  # 可选择显示字段
        # exclude = [‘price‘,]  # 排除字段

    def get_authors(self,obj):
        query_set = obj.authors.all()
        return [{‘name‘:obj.name} for obj in query_set]



{
    "id": 2,
    "authors": [
        {
            "name": "蒋勋"
        }
    ],
    "publisher": "长江出版社",
    "title": "蒋勋说唐诗",
    "pub_date": "2018-11-04",
    "word_count": 12,
    "price": 34
}

Drf 序列化 ModelSerializer跨表取数据

标签:lis   选择   tle   pytho   fun   clu   keyword   word   ring   

原文地址:https://www.cnblogs.com/YZL2333/p/11800323.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!