Django/DRF序列化

方式一:list()函数配合ORM中values()实现的序列化

book_list = list(Book.objects.all().values())

方式二:自己构造一个列表,将数据一条条取出,放入自己构造的空字典中,再将字典放入列表中

方式三:model_to_dict()

    from django.forms.models import model_to_dict
    books_obj = Book.objects.all()
    book_list = []
    for book in books_obj:
        book_list.append(model_to_dict(book))

 方式四:django序列化serializers

    from django.core import serializers
    book_obj = Book.objects.all()
    book_list = serializers.serialize("json", book_obj)

   !!!django序列化取不到字段中choice属性的值

方式五:django rest framework的序列化serializers.Serializer

  新建一个serializer.py

from rest_framework import serializers
from .models import *
class BookSerializer(serializers.Serializer):
    id = serializers.IntegerField(required=False)
    title = serializers.CharField(max_length=32, validators=[my_validate])
    CHOICES = ((1, "Python"), (2, "Go"), (3, "Linux"))
    category = serializers.ChoiceField(choices=CHOICES, source="get_category_display", read_only=True)
    w_category = serializers.ChoiceField(choices=CHOICES, write_only=True)
    pub_time = serializers.DateField()

    publisher = PublisherSerializer(read_only=True)
    publisher_id = serializers.IntegerField(write_only=True)
    author = AuthorSerializer(many=True, read_only=True)
    author_list = serializers.ListField(write_only=True)

    def create(self, validated_data):
        book = Book.objects.create(title=validated_data["title"], category=validated_data["w_category"],
                                pub_time=validated_data["pub_time"], publisher_id=validated_data["publisher_id"])
        book.author.add(*validated_data["author_list"])
        return book

    def update(self, instance, validated_data):
        instance.title = validated_data.get("title", instance.title)
        instance.category = validated_data.get("category", instance.category)
        instance.pub_time = validated_data.get("pub_time", instance.pub_time)
        instance.publisher_id = validated_data.get("publisher_id", instance.publisher_id)
        if validated_data.get("author_list"):
            instance.author.set(validated_data["author_list"])
        instance.save()
        return instance

    def validate_title(self, value):
        if "python" not in value.lower():
            raise serializers.ValidationError("标题必须含有python")
        return value

    def validate(self, attrs):
        if attrs["w_category"] == 1 and attrs["publisher_id"] == 1:
            return attrs
        else:
            raise serializers.ValidationError("分类以及标题不符合要求")

方式六:django rest framework的序列化serializers.ModelSerializer

  新建一个serializer.py

  # 我们可以自己定制想要序列化的内容

from rest_framework import serializers
from .models import *
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
        # fields = ["id", "title", "pub_time"]
        fields = "__all__"
        # depth = 1
        extra_kwargs = {"category": {"write_only": True}, "publisher": {"write_only": True},
                        "author": {"write_only": True}}

 

 

posted @ 2019-08-17 17:55  你有我备注吗  阅读(319)  评论(0编辑  收藏  举报