带有额外过滤器的Django查询集

时间:2015-08-24 20:17:55

标签: python django views django-queryset

我的models.py如下:

class Prescription(models.Model):
    date_prescribed = models.DateTimeField()
    doctor = models.ForeignKey(Doctor)  
    pharmacy = models.ForeignKey(Pharmacy)

class Doctor(models.Model):
    name = models.CharField(max_length=150)  
    age = models.PositiveSmallIntegerField()

class Pharmacy(models.Model):
    name = models.CharField(max_length=150)
    status = models.CharField()

我现在需要找到所有在六个月内按月分组的处方,今天的月份作为六个月的起始月份。我尝试在shell上播放一些并使这个查询工作:

end_date = timezone.now()
start_date = end_date - relativedelta(months=6)    
qs = (Prescription.objects.extra(select={'month': connection.ops.date_trunc_sql('month', 'date_prescribed')})
                            .filter(date_prescribed__range=(start_date,end_date))
                            .annotate(Count('id'))
                            .order_by('month'))

但是,在视图中使用时也不起作用:

class PrescriptionTrendListView(generics.ListAPIView):
    queryset = Prescription.objects.all()
    serializer_class = LineGraphSerializer

    def get_queryset(self):
        end_date = timezone.now()
        start_date = end_date - relativedelta(months=6)
        truncate_date = connection.ops.date_trunc_sql('month', 'date_prescribed')
        qs = super(PrescriptionTrendListView,self).get_queryset.extra(select={'month': truncate_date})
        return qs.filter(date_prescribed__range=(start_date, end_date)).annotate(pk_count=Count('pk')).order_by('month')

我收到错误声明"函数对象没有额外的属性" 。 我做错了什么?

0 个答案:

没有答案