带有额外过滤器的 Django 查询集
Django queryset with extra filter
我的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()
我现在需要找到六个月内按月分组的所有处方,以今天的月份为开始月份,可以追溯到六年前 month.I 尝试在 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')
我收到错误消息 "function object has no attribute extra"。
我做错了什么?
你的超级函数调用有错字(你没有调用它)
qs = super(PrescriptionTrendListView,self).get_queryset().extra(select={'month': truncate_date})
我的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()
我现在需要找到六个月内按月分组的所有处方,以今天的月份为开始月份,可以追溯到六年前 month.I 尝试在 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')
我收到错误消息 "function object has no attribute extra"。 我做错了什么?
你的超级函数调用有错字(你没有调用它)
qs = super(PrescriptionTrendListView,self).get_queryset().extra(select={'month': truncate_date})