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)
1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.