0

How can I choose by what var value that I get by filter that then to append a value in the loop?

items = Item.objects.filter(Q(var__icontains=term) | Q(another_var__icontains=term))
res = []
for item in items:
    res.append({
        'val': item.(var or another_var?),
    })
Tomasz Jakub Rup
  • 10,502
  • 7
  • 48
  • 49
jwshadow
  • 107
  • 11

2 Answers2

0

I am afraid that you have to check var/anohter_var manually to find which variable is matched in the queryset.

items = Item.objects.filter(Q(var__icontains=term) |
                            Q(another_var__icontains=term))
uterm = term.upper()
res = []
for item in items:
    value = item.var if uterm in item.var.upper() else item.another_var
    res.append({'val': value})
catavaran
  • 44,703
  • 8
  • 98
  • 85
0

Check it locally, or do two different queries. First option:

items = Item.objects.filter(Q(var__icontains=term) | Q(another_var__icontains=term))
res = []
for item in items:
    if term.lower() in item.var.lower():
        v = item.var
    else:
        v = item.another_var
    res.append({
        'val': v,
    })

Second option, just do two queries (two filter calls).

eran
  • 6,731
  • 6
  • 35
  • 52