Lukor
Lukor

Reputation: 1727

Overwrite field in queryset annotate

I have a django model with the fields name (string) and value (integer). Say I need to return a queryset of {name:..., value:...} objects, with each value doubled. What I am trying to do now is:

queryset.annotate(value=F('value') * 2)

However, django tells me that the field value already exists.

I also tried using extra:

queryset.annotate(value_double=F('value') * 2).extra(select={'value': 'value_double'})

but that also does not work since value_double is not a valid field.

Of course, in this case I could use something like queryset.extra(select={'value': 'value * 2'}), but I have some other, more complicated cases involving a lot of functions where I really don't want to write sql, but I'd rather find a solution in django. Again, in all of my cases, annotate works perfectly fine as long as I give the result a new name.

Upvotes: 6

Views: 3405

Answers (1)

Anupam Chaplot
Anupam Chaplot

Reputation: 1316

Say your model is XYZ with fields name and val. If you want val to contain val*2 use below queryset

x = XYZ.objects.values('name').annotate(val=F('val')*2)

print(x)

Result

<QuerySet [{'name': abc, 'val': 104},...............] 

If you want queryset that return name,val and doubleval. You can use below query for same.

x = XYZ.objects.values('name','val',doubleval=F('val')*2)
print(x)

Result

<QuerySet [{'name': abc, 'val':52,'doubleval': 104},...............] 

Hope this help.

Upvotes: 5

Related Questions