2015-11-02 128 views
2

如何在初始查詢後過濾查詢集?基本上,我試圖從查詢集中刪除一個項目(不從數據庫中刪除它)。如何過濾Django Queryset

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

回答

1

您可以將Manager的方法應用於QuerySet對象。

第一:

.all()末不需要在:

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

二:

如果你想排除從queryset的一個對象,你可以使用:

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

第三張:

對於你的情況,你可以用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) 
+0

排除的問題是我需要排除基於兩個值:first_name_lower和last_name lower,因此我需要刪除典型排除之外的queryset項目。 –

0

這樣,你不應該使用的查詢集API。在你的情況,你只需要使用Q對象來過濾company_account

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

或者更好,使用全文搜索方法。或者使用原始的SQL查詢。

相關問題