【Django】drf serializer序列化

文章目录

      • model中字段属于外键的情况,序列化想展示外键表中的某个字段
      • 某些序列化字段需要特殊处理,可以自定义方法处理
      • model 字段有choices,如何序列化
      • model 多对多字段的序列化

model中字段属于外键的情况,序列化想展示外键表中的某个字段

A表的model结构如下

class OTAProductModel(BaseMysqlModel):
    id = models.AutoField(primary_key=True, verbose_name="id")
    ota = models.ForeignKey('OTAModel', on_delete=models.CASCADE, related_name='ota_product', verbose_name="平台")
    name = models.CharField(max_length=64, verbose_name="产品名称")
    code = models.CharField(max_length=64, unique=True, verbose_name="产品编码")
    history = HistoricalRecords(excluded_fields=['create_time', 'update_time'])

    class Meta:
        verbose_name = '平台产品管理'
        verbose_name_plural = verbose_name

    def __str__(self):
        return '%s(%s)' % (self.name, self.ota)

关联的外键表 结构如下


class OTAModel(BaseMysqlModel):
    id = models.AutoField(primary_key=True, verbose_name="id")
    name = models.CharField(max_length=64, verbose_name="平台名称")
    code = models.CharField(max_length=64, verbose_name="平台编号")
    history = HistoricalRecords(excluded_fields=['create_time', 'update_time'])

    class Meta:
        verbose_name = '平台管理'
        verbose_name_plural = verbose_name

    def __str__(self):
        return '%s(%s)' % (self.name, self.code)

想要的效果,在序列化A表时,展示出外键表B中的name,code字段,可以这样操作
在A表的序列话文件中

class OTAProductSerializer(serializers.ModelSerializer):
    create_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True)
    update_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True)
    ota_name = serializers.CharField(source='ota.name', read_only=True)
    ota_code = serializers.CharField(source='ota.code', read_only=True)
    message = OtaProductPromptMessageSerializer(many=True)

    class Meta:
        model = OTAProductModel

        fields = '__all__'

ota_name = serializers.CharField(source=‘ota.name’, read_only=True),需要注意两个地方,其中ota.name的ota是A表的model字段名称,name是外键表B中的字段名称

某些序列化字段需要特殊处理,可以自定义方法处理

from rest_framework import serializers

from project.models.project import ProjectModel


class ProjectSerializer(serializers.ModelSerializer):
    principal_username = serializers.CharField(source='project_principal.cn', read_only=True)
    progress_word = serializers.SerializerMethodField()

    class Meta:
        model = ProjectModel

        exclude = ['create_time', 'update_time']

    def get_progress_word(self, instance):
        progress = instance.progress
        word = ''
        if 0 <= progress and progress <= 5:
            word = '购前论证'
        elif 5 < progress and progress <= 15:
            word = '立项请示'
        elif 15 < progress and progress <= 30:
            word = '事前申请'
        elif 30 < progress and progress < 40:
            word = '采购计划'
        elif 40 < progress and progress <= 55:
            word = '招标采购'
        elif 55 < progress and progress <= 60:
            word = '中标'
        elif 60 < progress and progress <= 65:
            word = '合同签订'
        elif 65 < progress and progress <= 70:
            word = '合同备案'
        elif 70 < progress and progress <= 75:
            word = '项目实施'
        elif 75 < progress and progress <= 80:
            word = '验收'
        elif 80 < progress and progress <= 90:
            word = '监管验收'
        elif 90 < progress and progress <= 95:
            word = '固定资产报增'
        elif 95 < progress:
            word = '报账'
        return word

【Django】drf serializer序列化_第1张图片
【Django】drf serializer序列化_第2张图片

需要注意的地方,如上图

model 字段有choices,如何序列化

model表

class PaymentModel(BaseMongoModel):
    """
    支付列表
    """
    SALETYPE = ((1, u'一次销售'),
                (2, u'二次销售'))
    sale_type = IntField(required=True, verbose_name='支付订单的订单类型', default=1, choices=SALETYPE)
    class Meta:
        verbose_name = '支付记录'
        verbose_name_plural = verbose_name

    def __str__(self):
        return '%s' % (self.serial_number,)

序列化sale_type字段,可以这么操作

class PaymentSerializer(ser.DocumentSerializer):
    sale_type_name = serializers.CharField(source='get_sale_type_display', read_only=True)

    class Meta:
        model = PaymentModel
        fields = '__all__'

需要注意:source的格式:get_model的字段名_display

model 多对多字段的序列化

model

class EntranceModel(BaseModel):
    name = models.CharField(max_length=128, verbose_name="入口名称")
    depts = models.ManyToManyField('user.DeptModel', related_name='entrances', verbose_name='部门')
    longitude = models.FloatField(null=True, blank=True, verbose_name='经度')
    latitude = models.FloatField(null=True, blank=True, verbose_name='纬度')

    class Meta:
        verbose_name = '部门入口配置表'
        verbose_name_plural = verbose_name
        app_label = 'entrance'

Serializer

import logging

from rest_framework import serializers

from entrance.models import EntranceModel
from user.models import DeptModel

logger = logging.getLogger('system')
class EntranceSerializer(serializers.ModelSerializer):
    depts = serializers.PrimaryKeyRelatedField(many=True, allow_empty=True, allow_null=True, required=False,
                                               queryset=DeptModel.objects.all())
    depts_name = serializers.SerializerMethodField()

    class Meta:
        model = EntranceModel
        fields = '__all__'

    def get_depts_name(self, instance):
        names = instance.depts.all().values_list('name', flat=True)
        return ','.join(names) if names else None

你可能感兴趣的:(Django,django)