2014-11-06 110 views
3

考慮以下幾點:鏈接過濾器一起

instances = Catalog.objects.filter(
           Q(imdb_url=imdb_url) 
           |Q(isan=isan) 
           |Q(amg_video_id=amg_video_id) 
) 

我怎麼會做同樣的格式如下,一起鏈每個:

instances = Catalog.objects.all() 
if imdb_url: 
    instances = instances.filter(imdb_url = imdb_url) # OR 
if isan: 
    instances = instances.filter(isan = isan) # OR 
if amg: 
    instances = instances.filter(amg = amg) # OR 

上面給我的等值:

instances = Catalog.objects.filter(imdb_url=imdb_url).filter(isan=isan).filter(amg=amg) 

我該如何處理第一個查詢中的Q的等價物?

回答

1

您可以創建一個空Q對象,或與他人從而用|=

q = Q() 

if imdb_url: 
    q |= Q(imdb_url=imdb_url) 
if isan: 
    q |= Q(isan=isan) 
if amg: 
    q |= Q(amg=amg) 

instances = Catalog.objects.filter(q) 
1

的查詢集union運算符是|

instances = Catalog.objects.none() 
if imdb_url: 
    instances |= instances.filter(imdb_url=imdb_url) 
if isan: 
    instances |= instances.filter(isan=isan) 
if amg: 
    instances |= instances.filter(amg=amg)