Django: '<' not supported between instances of 'User' and 'User'

Viewed 134

When I do:

    qs1 = User.objects.filter(first_name__icontains=search).filter(is_superuser=False)
    qs2 = User.objects.filter(last_name__icontains=search).filter(is_superuser=False)
    users = sorted(set(chain(qs1, qs2)))

I get this error:

'<' not supported between instances of 'User' and 'User'
2 Answers

try something like this

qs1 = User.objects.filter(first_name__icontains=search).filter(is_superuser=False)
qs2 = User.objects.filter(last_name__icontains=search).filter(is_superuser=False)

qs1 = qs1.values_list('id', flat=True)
qs2 = qs1.values_list('id', flat=True)

users = sorted(set(chain(list(qs1), list(qs2))))

Chaining Querysets is typically not a good idea, since you can not filter these further, annotate these, and furthermore it results in two (or more) queries.

You can combine the two QuerySets with:

from django.db.models import Q

User.objects.filter(
    Q(first_name__icontains=search) | Q(last_name__icontains=search),
    is_superuser=False
).order_by('pk')

This will result in a single query where the elements are User objects.

Related