• 序列化类补充 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
            })
  • 相关阅读:
    oracle--单表查询
    oracle--本地网络配置tnsnames.ora和监听器listener.ora
    HDU1251统计难题(字典树Trie Tree好题)
    模板——字典树Trie Tree
    51nod——1277 字符串中的最大值
    KMP——hdu 3336 count the string
    KMP模板
    KMP——Game
    BFS——Weed
    DFS——Sum It Up
  • 原文地址:https://www.cnblogs.com/ludingchao/p/12507753.html
Copyright © 2020-2023  润新知