Kamil
Kamil

Reputation: 59

Django group by with variable

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

In this example I would like to pass values by variable, in previous lines I have some if's and depends on it I need to group by my results. Instead of 'month','location' there should be variable like my_list. I tried to convert it with join and map, but every time I get an error.

Upvotes: 3

Views: 249

Answers (2)

Nikita
Nikita

Reputation: 6331

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

Upvotes: 3

ilse2005
ilse2005

Reputation: 11429

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

Upvotes: 3

Related Questions