zoukankan      html  css  js  c++  java
  • 序列化类补充 source关键字参数 SerializerMethodField方法

    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表,等同于子序列化
        parent_id = serializers.SerializerMethodField() # 给自定义字段定义规则
    
        def get_parent_id(self,obj):        # 必须以get开头定义parent_id的获取属性,obj是每条记录
            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
            })
  • 相关阅读:
    CF238B Boring Partition
    CF1424G Years
    CF995D Game
    CF468C Hack it!
    CF1417A Copy-paste
    CF1417B Two Arrays
    CF849B Tell Your World
    [洛谷P3389][模板]高斯消元法
    CF1225D
    P6687
  • 原文地址:https://www.cnblogs.com/ludingchao/p/12507753.html
Copyright © 2011-2022 走看看