其他分享
首页 > 其他分享> > ModelSerializer反序列化和序列化

ModelSerializer反序列化和序列化

作者:互联网

class BookSerializer(serializers.ModelSerializer):
    category_display = serializers.SerializerMethodField(read_only=True)
    publisher_info = serializers.SerializerMethodField(read_only=True)
    authors = serializers.SerializerMethodField(read_only=True)

    def get_category_display(self, obj):
        return obj.get_category_display()

    def get_authors(self, obj):
        authors_query_set = obj.author.all()
        return [{"id": author_obj.id, "name": author_obj.name} for author_obj in authors_query_set]

    def get_publisher_info(self, obj):
        # obj 是我们序列化的每个Book对象
        publisher_obj = obj.publisher
        return {"id": publisher_obj.id, "title": publisher_obj.title}

    class Meta:
        model = Book  # 告诉它对应的model
        # fields = ["id", "title", "pub_time"]
        fields = "__all__"
        # depth = 1
        extra_kwargs = {"category": {"write_only": True}, "publisher": {"write_only": True},
                        "author": {"write_only": True}}

 

标签:publisher,obj,author,only,ModelSerializer,序列化,True,id
来源: https://www.cnblogs.com/zhoulixiansen/p/11147670.html