DjangoRestFrameworkNotes

title: Django Rest Framework ็ฌ”่ฎฐ tags:

  • Django

  • Django Rest Framework

    categories:

  • Python

Serializers

RelationShip

# coding: utf-8
# @author   bovenson
# @email    [email protected]
# @desc     Django Rest Framework Serializers

from rest_framework import serializers
from book.models import *
from cloudlibraryserver.settings import IMAGE_SOURCE, IMG_URL


class ScoreSerializer(serializers.ModelSerializer):
    """ไนฆ็ฑ่ฏ„ๅˆ†"""
    class Meta:
        model = BookScore
        fields = '__all__'


class BookAuthorSerializer(serializers.ModelSerializer):
    """ไนฆ็ฑไฝœ่€…"""
    class Meta:
        model = BookAuthor
        fields = '__all__'


class BookTagSerializer(serializers.ModelSerializer):
    """ไนฆ็ฑๆ ‡็ญพ"""
    class Meta:
        model = BookTag
        fields = '__all__'


class BookSerializer(serializers.ModelSerializer):
    """ไนฆ็ฑ"""
    score = ScoreSerializer(many=False, read_only=True)
    author = BookAuthorSerializer(many=True, read_only=True)
    tags = BookTagSerializer(many=True, read_only=True)

    class Meta:
        model = Book
        fields = ['name', 'summary', 'pic', 'score', 'author', 'tags']

    def to_representation(self, instance):
        # ไฟฎๆ”นๅ›พ็‰‡URL
        ret = super().to_representation(instance)
        # ไธƒ็‰›ๅ‚จๅญ˜
        if IMAGE_SOURCE == 'QINIU':
            ret['pic'] = IMG_URL + ret['pic'][len('/media'):]
        return ret


class BooklistSerializer(serializers.HyperlinkedModelSerializer):
    """ไนฆๅ•"""
    class Meta:
        model = BookList
        fields = ['id']

Order

่Žทๅ–ๅ•ไธช่ฎฐๅฝ•

่ฎพ็ฝฎModelViewSetไน‹ๅŽ๏ผŒไผš้ป˜่ฎคๅขžๅŠ view_url/pk/

ไฝฟ็”จไธๅŒSerilizerๅŒไธ€ๆจกๅž‹

urls.py

่ฟ”ๅ›žๆ ‘

้œ€ๆฑ‚ๆ่ฟฐ

่ฟ”ๅ›žๆ•ฐๆฎๅบ“่กจไธญๆ่ฟฐ็š„ๅˆ†็ฑปๆ ‘

Model

Serializer

ViewSet

้ข„่งˆ

GET /api/article/category/tree/

ๅˆ†้กต

File Tree

่‡ชๅฎšไน‰ๅˆ†้กต็ฑป

pagination.py

settings

ๅฏนไบŽ่‡ชๅฎšไน‰action่ฟ›่กŒๅˆ†้กต

ๅ‚่€ƒ

ๆœ€ๅŽๆ›ดๆ–ฐไบŽ

่ฟ™ๆœ‰ๅธฎๅŠฉๅ—๏ผŸ