Barak Hartman
Barak Hartman

Reputation: 31

Django annotation in a loop

I'm trying to create an unknown amount of columns with annotate:

def add_daily_usage_record(query, days):

   for i in days:
       query.annotate('day_' + i + '_usage'= "doesn't matter"

But it doesn't seem to work. Is there any way to give an annotation a name without writing it? or maybe if I have the name of the new column in a variable, is it possible to pass it to annotate?

Thank you.

Upvotes: 3

Views: 2081

Answers (2)

user2390182
user2390182

Reputation: 73460

You can use dict unpacking with the ** operator to provide dynamic keyword arguments to any function and you should probably reassign the query:

query = query.annotate(**{'day_' + i + '_usage': "doesn't matter"})

Upvotes: 4

Jason
Jason

Reputation: 11363

When you do an annotation or other operation on a queryset, it returns a new instance of the queryset. It doesn't modify the previous queryset.

So change your statement in the loop to

query = query.annotate(...)

Upvotes: 1

Related Questions