2015-08-25 114 views
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) 

作品真的很好,输出我得到当我访问的网址如下: enter image description here

目前开始和结束日期是硬编码和处方数是所有医生和pharmacies.However,我现在需要过滤的3个参数的基础上的结果:

  1. 医生
  2. 药房
  3. Start_dat日期和结束日期

我想在这样的网址添加这些参数:

MYAPP /服务/概述医生=约翰&药房= Phizer &起始日期= 2015年7月28日& END_DATE = 2015年2月12日

如何捕捉到这些参数和动态改变的URL参数的基础上,SQL查询?

回答

0
Rest framework provide get_queryset method and overide it and implement 
the new functionality you want to. 

class PrescriptionTrendOverview(viewsets.ModelViewSet): 
    queryset = Prescription.objects.all() 
    serializer_class = PrescriptionSerializer 

    def get_queryset(self): 
     queryset = super(PrescriptionTrendOverview, self).get_queryset() 
     doctor_name = self.request.query_params.get('doctor', None) 
     pharmacy_name = self.request.query_params.get('pharmacy', None) 
     start_date = self.request.query_params.get('start_date', None) 
     end_date = self.request.query_params.get('end_date', None) 
     if doctor_name and pharmacy_name and start_date and end_date: 
      queryset = queryset.filter(
       Q(doctor__name=doctor_name) & Q(pharmacy__name=pharmacy_name) 
       & Q(date_prescribed__gte=start_date) & Q(date_prescribed__lte=end_date)) 
     # or another way of writing the queryset 
     queryset = queryset.filter(doctor__name=doctor_name, 
       pharmacy__name=pharmacy_name, ate_prescribed__gte=start_date, date_prescribed__lte=end_date) 
    return queryset