工作常见问题

1、四舍五入

import decimal

decimal.getcontext().rounding = decimal.ROUND_HALF_UP
a = str(decimal.Decimal(1.63333).quantize(decimal.Decimal("0.00")))
print(a)  # 1.63

2、使用orm写定时任务

# 第一部分:内置模块
import os 
import calendar
import json
import time

# 第二部分:django路径
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "application.settings")
django.setup()

# 第三部分:导入模型
from apps.web.utils.time_cycle import str_mk_day_time
from apps.web.wattendance.models.scheduling import Scheduling

# 第四部分:使用orm curd
...

 3、Django修改request属性时:This QueryDict instance is immutable

def medusa(request):
    request.POST._mutable = True

    # 或者是:
    # request.GET._mutable = True
复制代码

 4、多对多设置

        for i in get_obj:
            ids.append(i.id)
            task_time = json.loads(i.time)
            company_id = i.company_id
            dept_belong_id = i.dept_belong_id
            for j in task_time:
                c_time = j.get("time")
                now_time = datetime.now()
                nt = now_time.strftime("%Y-%m-%d")
                re_ctime = "%s %s,%s %s" % (nt, c_time[0], nt, c_time[1])
                task_obj = CleaningTask.objects.create(
                    area_id=i.id, cleaning_time=re_ctime, principal_id=i.principal_id,
                    company_id=company_id, dept_belong_id=dept_belong_id,
                    is_system=0, dept_name="", post_name="", task_state=1,
                    cleaning_picture="[]", cleaning_check_picture="[]",
                    create_datetime=now_time, principal=json.dumps({"id": i.principal_id, "username": i.principal.name})
                )
         # 多对多设置 task_obj.staff.set(i.staff.all())
# 新建时生成保洁通知 Notice7Tool(None, company_id).sendNotice(task_obj.id)

 5、常用正则

        # 校验车牌
        pattern = re.compile(r'^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$',
                             re.I)  # re.I 表示忽略大小写
        m = pattern.match(request.data.get('car_number'))
        if m is None:
            msg = "车牌非法,不可进入"
# 校验手机号
pattern = r'^1[3-9]\d{9}$'
phone_number = '13812345678'
if re.match(pattern, phone_number):
    print('匹配成功')
else:
    print('匹配失败')

6、Django的orm查询优化

# {id:parentId, id:parentId}
dept_dict = dict(
    Dept.objects.filter(
        is_delete=0,
        company_id=company_id,
        status="1"
    ).values_list("id", "parentId")
)

# 统计表记录中金额
sum_money = LeaseContractDetails.objects.aggregate(
    breach_money=Sum("overdue_charge"),
    pay_money=Sum("pay_charge")
)


# 按字段分组查询
queryset_month = DealCount.objects.values("belong_date_str").annotate(
    total_entry_weight=Sum('entry_weight') / 1000,  # 进场商品
    total_out_weight=Sum('out_weight') / 1000,  # 出场商品
    total_market_stock=Sum('market_stock') / 1000,  # 市场存量
).order_by('-belong_date_int')

 

posted @ 2022-10-19 19:28  三三得九86  阅读(26)  评论(0)    收藏  举报