Drf 序列化 ModelSerializer跨表取数据

Posted yzl2333

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Drf 序列化 ModelSerializer跨表取数据相关的知识,希望对你有一定的参考价值。

 

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跨表取数据的主要内容,如果未能解决你的问题,请参考以下文章

DRF框架之ModelSerializer序列化器

DRF框架serializer之ModelSerializer

DRF ---- ModelSerializer

DRF序列化和反序列化(二:ModelSerializer)

drf高级五ModelSerializer

ModelSerializer组件