0
我的models.py如下:原始的SQL查询作为每个URL参数在Django
class Prescription(models.Model):
date_prescribed = models.DateField()
doctor = models.ForeignKey(Doctor)
pharmacy = models.ForeignKey(Pharmacy)
class Doctor(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
class Pharmacy(models.Model):
name = models.CharField(max_length=100)
status = models.Charfield(max_length=100)
我想在我的观点是认为通过一个月的最后六个月分组处方数的查询集。我现在用raw_sql和我的views.py如下:
from django.db import connection
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['GET'])
def prescription_trend_overview(request):
query = '''
select concat(year(rx.date_prescribed),'-',month(rx.date_prescribed)) as timeline,
COUNT(rx.id) as total_prescriptions
from myapp_prescription rx, myapp_doctor doctor, myapp_pharmacy pharmacy
where pharmacy.id = rx.pharmacy_id and
doctor.id = rx.doctor_id and
rx.date_prescribed >= '2014-06-04' and
rx.date_prescribed <= '2015-08-15'
group by timeline
order by year(rx.date_prescribed),
month(rx.date_prescribed)
'''
try:
cursor = connection.cursor()
cursor.execute(query)
descr = cursor.description
rows = cursor.fetchall()
result = [dict(zip([column[0] for column in descr], row)) for row in rows]
finally:
cursor.close()
return Response(result, status=status.HTTP_200_OK)
目前开始和结束日期是硬编码和处方数是所有医生和pharmacies.However,我现在需要过滤的3个参数的基础上的结果:
- 医生
- 药房
- Start_dat日期和结束日期
我想在这样的网址添加这些参数:
MYAPP /服务/概述医生=约翰&药房= Phizer &起始日期= 2015年7月28日& END_DATE = 2015年2月12日
如何捕捉到这些参数和动态改变的URL参数的基础上,SQL查询?