记一次:ORM查询到数据后,返回前端前,对数据做出修改
本次修改是直接在序列化中作出的修改
from app01.models import BusinessOpportunities, UserRecommendSetting class BusinessOpportunitiesSerializer(serializers.ModelSerializer): quantity = serializers.SerializerMethodField(method_name=None, read_only=True) # 字段初始化(这里的quantity可以不是数据库字段,
# 只存在于要返回的fields中,然后通过get_初始化的字段名(这里是get_quantity)进行数据库中取出的字段进行处理) class Meta: model = BusinessOpportunities fields = ('bo_id', 'bo_name', 'keywords', 'quantity', 'quantity_unit', 'tel', 'url') # 序列化 def get_quantity(self, obj): # 针对初始化后的字段做出修改 if obj.get('quantity') == -1: return '-' # 把数据中对应字段满足条件的值,把数据修改为 ‘-’ return obj.get('quantity') # 返回原始数据(不满足上述条件,返回本身数据库查出的值) class BusinessOpportunitiesDetailSerializer(serializers.ModelSerializer): quantity = serializers.SerializerMethodField(method_name=None, read_only=True) class Meta: model = BusinessOpportunities fields = '__all__' def get_quantity(self, obj): if obj.quantity == -1: return '-' return obj.quantity