1

I need to do something like this in order to match some objects. This is the best way to do it? Is possible to do it in a faster way?

if User.objects.filter(first_name=name, age=age).exists():
     user = User.objects.filter(first_name=name, age=age)
     function_x(user)
elif User.objects.filter(full_name__icontains=name, age=age).exists():
     user = User.objects.filter(full_name__icontains=name, age=age)
     function_x(user)
62009030
  • 347
  • 1
  • 5
  • 20
  • 1
    Possible duplicate of [Django Filters - or?](http://stackoverflow.com/questions/739776/django-filters-or) – Sayse Sep 05 '16 at 10:53

2 Answers2

2

If you want use one of that condition, just use Q object, it allows you use logic or operator in your query.

from django.db.models import Q

User.objects.filter(Q(first_name=name) |
                    Q(full_name__icontains=name),
                    age=age)

In that case | means or and , means and, so age is required in both conditions.

Ivan Semochkin
  • 8,649
  • 3
  • 43
  • 75
1

Given the variable name, I guess you are expecting the above query to return a single user. Thus, you can eliminate one more db hit using .first():

.first() basically returns the first object matched by the queryset, or None if there isn't one. By this way, you don't have to perform .exists().

user = User.objects.filter(Q(first_name=name) | Q(full_name__icontains=name), age=age).first()
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119