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

序列化类补充 source关键字参数 SerializerMethodField方法

时间:2020-03-16 23:47:22      阅读:78      评论:0      收藏:0      [点我收藏+]

标签:key   app   parent   ade   方法   自定义   method   url   get   

 

models.py

from django.db import models

class Category(models.Model):
    cat_id = models.AutoField(primary_key=True)
    category_name = models.CharField(max_length=50)
    parent = models.ForeignKey(to=Category, to_field=cat_id, related_name="Category", on_delete=models.CASCADE,
                               db_constraint=False, blank=True, null=True)
    p_order = models.IntegerField(default=0)
    is_show = models.BooleanField(default=1)
    image = models.OneToOneField(to=Images, to_field=image_id, on_delete=models.CASCADE, db_constraint=False,
                                 null=True)
    creat_time = models.DateTimeField(auto_now_add=True)
    update_time = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.category_name


class Images(models.Model):
    image_id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=30, default="0")
    image_url = models.ImageField(upload_to="")
    creat_time = models.DateTimeField(auto_now_add=True)
    update_time = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

 

Cate_ser.py

from rest_framework import serializers
from app01 import models

class Cate_ser(serializers.ModelSerializer):
    image_url = serializers.ImageField(source=image.image_url)    # source关联到image表,代替了models表中的property自定义字段
    parent_id = serializers.SerializerMethodField() # 给自定义字段定义规则

    def get_parent_id(self,obj):        # 必须以get开头定义parent_id的获取属性
        if obj.parent_id is None:
            return 0
        else:
            return obj.parent_id

    class Meta:
        model = models.Category
        fields = __all__

技术图片

 

category.py

from rest_framework.views import APIView
from rest_framework.response import Response
from app01 import models
from app01.my_ser import Cate_ser

class List(APIView):
    def post(self,request):
        data = models.Category.objects.filter(is_show=True)
        data = Cate_ser.Cate_ser(instance=data,many=True,context={request:request}).data
        return Response({
            code:200,
            msg:ok,
            data:data
        })

 

序列化类补充 source关键字参数 SerializerMethodField方法

标签:key   app   parent   ade   方法   自定义   method   url   get   

原文地址:https://www.cnblogs.com/ludingchao/p/12507753.html

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