I have a little bit complex query and I use annotate with a conditional expression, the code is below:
from django.db.models import Q, F, When, CharField, Value, Case
from django.contrib.auth.models import User
ATT_PREFIX = 'f'
def get_it(mymodel, fields):
q = Q(modelone__modeltwo__mymodel=mymodel)
query_set = {
'aid': F('modelone__id'),
'name': F('modelfour__name'),
}
for f in fields:
query_set[ATT_PREFIX + str(f.id)] = Case(
When(Q(modelfive__modelsix=f) &
Q(modelfive__user__email=F('email')),
then='modelfive__entry'),
default=Value(''),
output_field=CharField(),
)
return User.objects.filter(q).annotate(**query_set)
Attributes aid and name collected with F()
have expected values. Second part which use conditional expression have a problem: If feilds list contain 2 objects, then I have 2 User objects created by Case()
when condition is meet. So instead of one object with atributes (aid, name, f17, f18)
I got two objects:
obj1 attributes (aid, name, f17)
obj2 attributes (aid, name, f18)
Django 1.10, Python3.5