带有额外过滤器的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')

我得到错误声明"函数对象没有额外属性"。我哪里做错了?

你的超级函数调用有一个错别字(你没有调用它)

qs = super(PrescriptionTrendListView,self).get_queryset().extra(select={'month': truncate_date})

相关内容

  • 没有找到相关文章

最新更新