• django serializers使用 sql


    models.py
    shifts_choices = (
    (1,"白班"),
    (2,"夜班"),
    )
    warehousing_choices = (
    (1,"正常入库"),
    (2,"返工"),
    )
    no_warehousing_reason_choices = (
    (1,"待品质检验"),
    (2,"待报废"),
    (3,"待客户检验"),
    )

    class ProductionHour(ZwBaseModel.BaseModel):
    production_date = models.DateField(null=True,verbose_name="生产日期")
    place = models.ForeignKey(OfficeAddressModels, on_delete=models.PROTECT, verbose_name="厂区")
    customer_name = models.CharField(max_length=20, verbose_name="客户名称")
    class_ban = models.CharField(max_length=20, verbose_name="班别")
    shifts = models.PositiveSmallIntegerField(choices=shifts_choices, default=1, verbose_name="班次")
    prodiction_order = models.CharField(max_length=10, verbose_name="生产订单号")
    line_number = models.IntegerField(verbose_name="行号")
    product_encoding = models.CharField(max_length=20,verbose_name="产品编码")
    product_name = models.CharField(max_length=50,verbose_name="产品名称")
    people_number = models.IntegerField(null=True,verbose_name="总人数")
    people_labors = models.IntegerField(verbose_name="劳务工人数")
    people_workers = models.IntegerField(verbose_name="正式工人数")
    work_hours = models.IntegerField(verbose_name="作业工时(人/分钟)")
    machine_debug = models.IntegerField(verbose_name="机器调试")
    wait_outside_material = models.IntegerField(verbose_name="等外部材料")
    wait_inside_material = models.IntegerField(verbose_name="等内部材料")
    equipment_maintenance = models.IntegerField(verbose_name="设备维修")
    other_problem = models.IntegerField(verbose_name="其他")
    job_hours = models.DecimalField(max_digits=8,decimal_places=2,null=True,verbose_name="作业RT")
    labors_hours = models.DecimalField(max_digits=8,decimal_places=2,verbose_name="劳务工时")
    workers_hours = models.DecimalField(max_digits=8,decimal_places=2,verbose_name="正式工时")
    working_hours = models.DecimalField(max_digits=8,decimal_places=2,verbose_name="作业工时")
    product_loss_time = models.DecimalField(max_digits=8,decimal_places=2,verbose_name="生产损时")
    sum_working_hours = models.DecimalField(max_digits=8,decimal_places=2,verbose_name="总工时")
    production_number = models.IntegerField(verbose_name="生产数量")
    warehousing_number = models.IntegerField(verbose_name="入库数量")
    no_warehousing_number = models.IntegerField(null=True,verbose_name="未入库数量")
    warehousing_encoding = models.CharField(max_length=100, null=True, verbose_name="入库编码")
    no_warehousing_reason = models.PositiveSmallIntegerField(choices=no_warehousing_reason_choices, null=True, verbose_name="未入库原因")
    warehousing_type = models.PositiveSmallIntegerField(choices=warehousing_choices, null=True, verbose_name="入库类型")
    rework_reason = models.CharField(max_length=40, null=True, verbose_name="返工/报废原因")
    remarks = models.CharField(max_length=100, null=True, verbose_name="备注")
    class Meta:
    db_table = 'OperateList_ProductionHour'
    views.py

    class ProductionsListView(ViewSet, ZwSqlMixin, generics.ListCreateAPIView):
    model_class = ProductionHour
    pkValue = 'id'
    mainTable = 'z'
    menuid = 422
    keywords = ["officeaddressname", "class_ban", "prodiction_order", "line_number", "product_encoding", "product_name"]
    querySql = """
    select * from (
    select a.id,a.creator,a.created,a.modifier,a.production_date,a.customer_name,a.class_ban,if(a.shifts=1,"白班","夜班") as shifts,a.prodiction_order,
    a.line_number,a.product_encoding,a.product_name,a.people_number,a.people_labors,a.people_workers,a.work_hours,a.machine_debug,
    a.wait_outside_material,a.wait_inside_material,a.equipment_maintenance ,a.other_problem ,a.job_hours ,a.labors_hours,
    a.workers_hours ,a.working_hours ,a.product_loss_time ,a.sum_working_hours ,a.production_number ,a.warehousing_number,
    a.no_warehousing_number ,a.warehousing_encoding ,a.no_warehousing_reason ,if(a.warehousing_type=1,"正常入库","返工") as warehousing_type,
    case
    when a.rework_reason=1 then '待品质检验' when a.rework_reason=2 then '待报废' when a.rework_reason=3 then '待客户检验' END as rework_reason,a.remarks ,
    h.officeaddressname as officeaddressname from OperateList_ProductionHour as a
    INNER JOIN OfficeAddress_officeaddressmodels as h on a.place_id = h.id
    ) z

    """

    # case when a.rework_reason=1 then '待品质检验' when a.rework_reason=2 then '待报废' when a.rework_reason=3 then '待客户检验' END as rework_reason   三元组 获取数据
    #if(a.shifts=1,"白班","夜班") as shifts 二元组获取数据

    dateLap = 'production_date'

        
        
    def fetchData(self,request):
    total = self.get_queryset()
    with connections['default'].cursor() as cursor:
    print(self.querySqlHolder)
    cursor.execute(self.querySqlHolder)
    raw_data = dictfetchall(cursor)
    for data in raw_data:
    data['created'] = datetime.datetime.strftime(data['created'], "%Y-%m-%d %H:%M:%S") if isinstance(data['created'], datetime.date) else ''
    if total >= 0:
    ret = {'total': total, 'rows': raw_data}
    else:
    ret = {'total': len(raw_data), 'rows': raw_data}
    return ret

    def list(self, request, *args, **kwargs):
    ret = self.fetchData(self.request)
    return Response(ret, status=status.HTTP_200_OK)
       def export(self, request):  # 下载
       ret = self.fetchData(self.request)
      data = loads(dumps(ret['rows'], cls=DecimalEncoder))
       columns = FieldSheetModel.objects.filter(menuid_id=self.menuid).values('name', 'showname','fieldtype').order_by('sort')
      rep = ExportFile().export(data, columns, '1.xls')
      return rep


    def create(self, request, *args, **kwargs):
    request_data = request.data.copy()
    request_data['creator'] = request.user.username
    request_data['created'] = datetime.datetime.now()
    ser = ProductionListSerializers(data=request_data)
    if ser.is_valid():
    ser.save()
    return Response(data=ser.data,status=status.HTTP_200_OK)
    return Response(data=ser.errors,status=status.HTTP_400_BAD_REQUEST)

    def destroy(self, request):
    try:
    queryParams = request.query_params['ids'].split(',')
    pk = "%s__in" % self.pkValue
    param = {pk: queryParams}
    queryData = self.model_class.objects.filter(**param)
    queryData.delete()
    return Response("删除成功", status=status.HTTP_200_OK)
    except:
    return Response(u'删除失败', status=status.HTTP_400_BAD_REQUEST)


    class ProductionListView(ViewSet, ZwSqlMixin):
    def retrieve(self, request, id):
    team = ProductionHour.objects.get(pk=id)
    if team:
    production = ProductionListSerializers(instance=team)
    return Response(production.data,status=status.HTTP_200_OK)
    else:
    return Response("数据不存在", status=status.HTTP_404_NOT_FOUND)

    def update(self, request, id):
    if id:
    pro = ProductionHour.objects.get(pk=id)
    request_data = request.data.copy()
    request_data['modifier'] = request.user.username
    production = ProductionListSerializers(instance=pro, data=request_data)
    # print(production)
    if production.is_valid():
    production.save()
    return Response("编辑成功", status=status.HTTP_200_OK)
    return Response(data=production.errors, status=status.HTTP_400_BAD_REQUEST)
    else:
    return Response("请输入id")

    serializers
    1.第一种写法
    class
    ProductionListSerializers(serializers.ModelSerializer): place_name = serializers.CharField(source='place.officeaddressname', required=False) #厂区名称 外键关联厂区 直接通过place.officeaddressname拿去名称 no_warehousing_reason_dis = serializers.SerializerMethodField() #未入库原因 命名不要和数据库字段冲突 warehousing_type_dis = serializers.SerializerMethodField() #入库类型 shifts_dis = serializers.SerializerMethodField() #班次 class Meta: model = ProductionHour fields = '__all__' def get_warehousing_type_dis(self, obj): #返回 no_warehousing_reason 未入库原因 return obj.get_warehousing_type_display() def get_no_warehousing_reason_dis(self, obj): #返回warehousing_type 入库类型 return obj.get_no_warehousing_reason_display() def get_shifts_dis(self, obj): #返回shifts 班次 return obj.get_shifts_display()



    2.第二种写法
    class ProductionListSerializers(serializers.ModelSerializer):
        place_name = serializers.CharField(source='place.officeaddressname', required=False)  #厂区名称
        no_warehousing_reason_dis = serializers.CharField(source='no_warehousing_reason_display')  #未入库原因
        warehousing_type_dis = serializers.CharField(source='get_warehousing_type_display')    #入库类型
        shifts_dis = serializers.CharField('get_shifts_display')    #班次
        class Meta:
            model = ProductionHour
            fields = '__all__'
    
    






     urls.py  
    url(r'^/prodictionlist/(?P<id>d+)', views.ProductionListView.as_view({'get': 'retrieve', 'put': 'update'})),    #详细单条数据
    url(r'^/prodictionslist$', views.ProductionsListView.as_view({'get': 'list', 'post': 'create', 'delete': 'destroy'})), #所有数据
    url(r'^/prodictionslist/export', views.ProductionsListView.as_view({'get':'export'})),
  • 相关阅读:
    图基础模板
    POJ 2528 Mayor's posters(线段树+离散化)
    POJ 3468 A Simple Problem with Integers(线段树)
    poj 2251 Dungeon Master
    nyoj 540 奇怪的排序
    hdoj 1253 胜利大逃亡
    hdoj 2612 Find a way【bfs+队列】
    nyoj 915 +-字符串
    hdoj 1242 Rescue
    nyoj 1022 最少步数【优先队列+广搜】
  • 原文地址:https://www.cnblogs.com/zxs117/p/12604485.html
Copyright © 2020-2023  润新知