django获取choices的显示值
1,models.py
#订单表 class Orders(models.Model): status_cat = ( ('0', '待装货'), ('1', '正在运输'), ('2', '已到达目的地'), ) orders_status = ( ('0', '待接单'), ('1', '已完成'), ) order_num = models.CharField(max_length=255,verbose_name='订单编号') order_car = models.CharField(max_length=255,verbose_name='运输车辆') o_price = models.DecimalField(max_digits=10, decimal_places=2,verbose_name='总价') o_status = models.IntegerField(default=0,verbose_name='运输状态',choices=status_cat) order_status = models.IntegerField(default=0,verbose_name='订单状态',choices=orders_status) s_user_type = models.IntegerField(verbose_name='所属货主') # 所属App_Client_User o_user_type = models.IntegerField(verbose_name='所属车主') # 所属App_Client_User
2.serializers.py
class OrdersSerializers(serializers.ModelSerializer): #定义内置类 class Meta: #指定序列化的字段 model = Orders #取所有的字段 fields = "__all__" o_status = serializers.SerializerMethodField() def get_o_status(self,row): if row.o_status == 0: status = '待装货' return status elif row.o_status == 1: status = '正在运输' return status elif row.o_status == 2: status = '已到达目的地' return status order_status = serializers.SerializerMethodField() def get_order_status(self,row): if row.order_status == 0: status = '待接单' return status elif row.order_status == 1: status = '已完成' return status
3.views.py
#我的货单 class My_orders(APIView): def post(self,request): data = {} try: ret = request.POST.get("token") ret = jwt.decode(ret,'secret_key',algorithms=['HS256']) result = App_Client_User.objects.get(u_phone=ret['u_name']) if result.user_type == 8: data['code'] = StatusEnum.SUCCESS.value data['mes'] = CodeEnum.SUCCESS.value res = Orders.objects.filter(s_user_type = result.id) ser = serializers.OrdersSerializers(many=True,instance=res) data['data'] = ser.data return JsonResponse(data) else: data['code'] = StatusEnum.SUCCESS.value data['mes'] = '您不是货主' return JsonResponse(data) except: data['code'] = StatusEnum.FAIL.value data['mes'] = CodeEnum.FAIL.value return JsonResponse(data)
结果:
{ "code": 200, "mes": "成功", "data": [ { "id": 1, "o_status": "待装货", "order_status": "待接单", "order_num": "k20190918", "order_car": "宁A8888", "o_price": "50000.00", "s_user_type": 9, "o_user_type": 6 }, { "id": 2, "o_status": "正在运输", "order_status": "已完成", "order_num": "k20190912", "order_car": "宁A9999", "o_price": "100000.00", "s_user_type": 9, "o_user_type": 6 } ] }