[Django]-Django group by with variable

3👍

Probably, you’re looking for unpacking. In case when a function expects separate arguments, and you have those arguments in a list or tuple you should use * to unpack the values as separate. There’s a similar syntax ** for the case with dictionaries.

In you case, try:

my_list = ['month', 'location']
truncate_date = connection.ops.date_trunc_sql('month', 'created')
qs = Order.objects.extra({'month':truncate_date})
report = qs.values(*my_list).annotate(Count('pk'))
👤Nikita

3👍

If you have a list of wanted values you can use the * syntax:

truncate_date = connection.ops.date_trunc_sql('month', 'created')
qs = Order.objects.extra({'month':truncate_date})
value_list = ['month', 'location']
report = qs.values(*value_list).annotate(Count('pk'))

Leave a comment