Search code examples
pythondjangoobjectfilterdjango-q

How many time can django objects.filter Q() be used in one query?


Given my user table has a big list of users which name can start with number or letter, how can I get users that name starts with A to Z?

I tried the following but it didn't work.

users = User.objects.filter(reduce(operator.or_, [Q(name__startswith=letter) for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ']))

However, if I tried the following, it worked

users = User.objects.filter(reduce(operator.or_, [Q(name__startswith=letter) for letter in 'ABCDEFGHI']))

It seems like the Q() is limited to 9 times in objects.filter. Could you please advise? Thanks!


Solution

  • Why don't you use the Regex filter?

    users = User.objects.filter(name__iregex=r'^[A-Z]')
    for user in users:
        print user.name
    

    Here is how I just tried in my local test django project: Just created a Model as:

    from django.db import models
    
    class Users(models.Model):
        name = models.CharField(max_length=50)
    

    Ran a django manage.py shell command, imported this model, and created, 3 users:

    >>>Users.objects.create(name="FirstUser").save()
    >>>Users.objects.create(name="SecondUser").save()
    >>>Users.objects.create(name="12NumberedUser").save()
    
    >>> for i in Users.objects.filter(name__iregex=r'^[A-Z]'):
    ...     print i.name
    ...
    FirstUser
    SecondUser
    >>>
    

    Also, for Q its the same way, but there is no need of Q if you have got only one condition.

    Hope that helps.