Reputation: 35
I want to count the filtered data and show it via Alert, but in my code count is not working. I also filter the date One day ahead the current date. How to work this?
def repairList(request):
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
dl1 = Repair.objects.filter(Deadline__date = datetime.datetime.today() + timedelta(days=1)).annotate(Count("id"))
print(dl1)
return render(request,'repair/repair_list.html',{'Title':'Repair List', 'dl1':dl1})
print output
<QuerySet [<Repair: VRR2020-000001>]>
Upvotes: 0
Views: 53
Reputation: 2120
If you want to just count filtered Repair
records you can use:
dl1_count = Repair.objects.filter(Deadline__date = datetime.datetime.today() + timedelta(days=1)).count()
print(dl1_count)
And printing the code of yours (I mean the line dl1 = Repair.objects.filter(Deadline__date = datetime.datetime.today() + timedelta(days=1)).annotate(Count("id"))
and print(dl1)
) does not show any result for that count because you have printed the queryset object so if you want to use your code you should change it to something like:
dl1 = Repair.objects.filter(Deadline__date = datetime.datetime.today() + timedelta(days=1)).annotate(Count("id"))
for obj in dl1:
print(obj.id__count)
because annotate adds that field to objects not to the queryset.
Upvotes: 0
Reputation: 4432
Probably it'll be easier to use aggregation (if you don't need original queryset, just append aggregation part):
dl1 = Repair.objects.filter(Deadline__date = datetime.datetime.today() + timedelta(days=1))
dl1_count = dl1.aggregate(counted=Count('id'))['counted'] # number of records
Upvotes: 1