Reputation: 1404
I have a queryset by doing:
chart_data = DetailChange.objects.extra(select={'day': 'date(captured_date)'})\
.values('item_id__store_id__store_name', 'day')\
.annotate(total_sale=Sum('amount_sold'))
then I have a queryset like this:
{'day': datetime.date(2019, 6, 24), 'item_id__store_id__store_name': 'Keyboard Pro', 'total_sale': 706.0}
{'day': datetime.date(2019, 6, 25), 'item_id__store_id__store_name': 'Keyboard Pro', 'total_sale': 18.0}
...
now what I want to do is get one single string that combines all the days in it, separated by ",". Like:
"2019-6-24, 2019-6-25, 2019-6-26, ..."
Is there an easy way to get it done?
Upvotes: 2
Views: 1957
Reputation: 42107
You can do it with genexp and str.join
with ,
as the separator:
', '.join(str(item['day']) for item in chart_data)
str(datetime.date)
i.e. datetime.date.__str__
already returns the date in %Y-%m-%d
format so you don't need to do any additional strftime
work.
OTOH, if you only need the day
field, you should not include item_id__store_id__store_name
in values
.
Upvotes: 3
Reputation: 477607
You can join the an iterable of formated date strings, like:
', '.join(item['day'].strftime('%Y-%-m-%-d') for item in chart_data)
So here we thus will format each day
object, like:
>>> dd.strftime('%Y-%-m-%-d')
'2019-6-24'
and we then join these together, separated by a comma and a space (', '
).
That being said, if you are only interested in formatting the date, it makes not much sense to first add extra annotations.
Upvotes: 1