Jeffrey Steven
Jeffrey Steven

Reputation: 195

How to Filter Django Queryset

How do I filter in a queryset after the initial query? Essentially I am trying to remove an Item from a queryset (without deleting it from the database).

accounts = company_account.objects.filter(company=userinfo.company).all()
    for account in accounts:
        if not search in account.first_name_lower+" "+account.last_name_lower:
            account.remove()

Upvotes: 2

Views: 1029

Answers (2)

Dmitry Astrikov
Dmitry Astrikov

Reputation: 657

You should not use queryset API in this way. In your case, you just need use Q object to filter your company_account:

accounts = company_account.objects.filter(
     Q(first_name_lower__icontain=search) |
     Q(last_name_lower__icontain=search),
     company=userinfo.company,
).distinct()

Or better, use full text search approach. Or use raw SQL query.

Upvotes: 0

Gocht
Gocht

Reputation: 10256

You can apply Manager's methods to a QuerySet objects.

First:

The .all() at the end is not needed in:

accounts = company_account.objects.filter(company=userinfo.company).all()
# this is the same that
accounts = company_account.objects.filter(company=userinfo.company)

Second:

If you want to exclude an object from the queryset, you can use:

accounts = accounts.exclude(**criteria**)

Third:

For your case, you could try this with Concat (Django 1.8+):

from django.db.models import Value, CharField
from django.db.models.functions import Concat

accounts.annotate(full_name=Concat('first_name_lower', Value(' '), 'last_name_lower'),
                  output_field=CharField()).exclude(full_name=something_here)

Upvotes: 1

Related Questions