Amistad
Amistad

Reputation: 7410

Django queryset with extra filter

My models.py is as follows:

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()

I need to now find all the prescriptions grouped by month over a period of six months with today's month as the starting month going back six month.I tried playing a bit on the shell and got this query working :

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'))

However,the same when used in a view does not work :

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')

I get the error stating that "function object has no attribute extra". What am I doing wrong ?

Upvotes: 0

Views: 676

Answers (1)

Mark Galloway
Mark Galloway

Reputation: 4151

You have a typo with your super function call (you're not calling it)

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

Upvotes: 2

Related Questions