django使用自定义sql

本文详细介绍了在Django框架中如何进行自定义SQL查询,包括如何执行复杂SQL、如何处理查询结果以及最佳实践,旨在帮助开发者更高效地利用Django进行数据库交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

from django.db import connection
from rest_framework.response import Response
# 查询
def search(date):
    # 年
    year = date[:3]
    # 月
    month = date[-2:]
    # 获取当月第一天的星期和当月的总天数
    first_day_weekday, month_range = calendar.monthrange(int(year), int(month))
    # 开始日期
    start_date = date + '01'
    # 截止日期
    end_date = date + str(month_range)
    # DB连接
    cursor = connection.cursor()
    # 业绩查询
    search_sql = 'SELECT tb.item1,ta.item2,' \
              ' ta.item3, ' \
              ' ta.item4, ' \
              ' ta.item5' \
              ' FROM B AS tb,A AS ta' \
              ' WHERE ta.key = tb.key ' \
              ' AND ta.date <= ' + end_date + ' AND ta.date >= ' + start_date + \
              ' GROUP BY tb.no ORDER BY tb.no '

    cursor.execute(search_sql )
    return_arr = cursor.fetchall()
    # 传回数据,cursor.fetchall后的结果集不带字符键,只能以下标取值
    result = []
    for item in return_arr:
        app_result = {
            'item1': item[0],
            'item2': item[1],
            'item3': item[2],
            'item4': item[3],
            'item5': item[4]
        }
        result.append(app_result)
    return Response({'result': result})

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值