Reputation: 602
how do I append a dictionary into a Django queryset? I did .values on the queryset already, but it still classifies as a queryset and when I try to use .append on it, this error came up
AttributeError: 'QuerySet' object has no attribute 'append'
Here is my code: (start and end are variables passed in to denote the start month and end month of the selected range)
qs = CustomerInformation.objects.filter(salesDepartment__in=[d]).filter(created_date__range=(start,end))
qs = qs.annotate(date=TruncMonth('created_date')).values('date').annotate(lead_count=Count('status',filter=Q(status="lead"))).annotate(client_count=Count('status',filter=Q(status="client")))
qs = qs.values('date', 'client_count', 'lead_count')
All I want to do is to add the missing dates to the queryset, like for example if my queryset has date: April 2020 and June 2020, but is missing May 2020 due to CustomerInformation not having any instances with created_date in range of May 2020, hence I want to be able to insert a dictionary with date: May 2020 and lead_count and client_count 0 so that my data visualisation would work properly
Thanks all, all help is appreciated!
Upvotes: 0
Views: 5293
Reputation: 806
You can not append to a qs, unless you're adding data to the database. If you want to you can convert to a list, then add items.
You could create a generator that outputs additional values where needed too.
Something like:
def getDatat():
qs = CustomerInformation.objects.filter(salesDepartment__in=[d]).filter(created_date__range=(start,end))
qs = qs.annotate(date=TruncMonth('created_date')).values('date').annotate(lead_count=Count('status',filter=Q(status="lead"))).annotate(client_count=Count('status',filter=Q(status="client")))
qs = qs.values('date', 'client_count', 'lead_count')
this_v = None
for next_v in qs:
if this_v is None:
this_v = next_v
yield this_v
continue
# Do logic for checking if there's any needed extra values between this_v and next_V
# yield extra values
this_v = next_v
yield this_v
Upvotes: 1