2013-02-20 31 views
2

比方說,我提出以下查詢:修改Django的QuerySet對象後,它已經創造了

showtimes = ShowTime.objects.filter(
    start_date__lte=start, 
    end_date__gte=end, 
    movie__slug=movie.slug, 
    city=city, 
    visible=1) 

現在我想有一個函數,它在queryset object和過濾還基於其他一些屬性的結果,是這樣的:

def is_subtitled_3d(showtimes): 
    return (
     showtimes.language == LANGUAGE_SUBTITLED and 
     showtimes.type_vip == None and 
     showtimes.type_3d == 1 and 
     showtimes.type_gtmax == None and 
     showtimes.type_xd == None) 

將類似的東西,工作修改對象還是有不同的方式做到這一點?

回答

3

查詢集是lazy and chainable

你可以過濾showtimes多次,只要你喜歡。我不相信你的語法是正確的,但你可以使用標準的filter保持過濾器的查詢集

def is_subtitled_3d(showtimes): 
    return showtimes.filter(
    language=LANGUAGE_SUBTITLED,   
    type_vip__isnull=True, 
    type_3d=1, 
    type_gtmax__isnull=True, 
    type_xd__isnull=True 
) 

也許,如果用戶想要過濾的3D電影,來說明如何可以合併過濾器,是這樣的:

showtimes = ShowTime.objects.filter(
    start_date__lte=start, 
    end_date__gte=end, 
    movie__slug=movie.slug, 
    city=city, 
    visible=1) 

if request.GET.get('is_3d_movie'): 
    showtimes = showtimes.filter(type_3d=1) 
etc... 
+0

這很好,正是我所需要的,謝謝包括文檔鏈接。 – edu222 2013-02-20 20:53:31

+0

順便說一句,使用'is__null'比使用'== None'更好嗎? – edu222 2013-02-20 20:58:05

+1

@ edu222嗯,我不知道'= None'究竟做了什麼,但是'isnull'會將你的查詢翻譯成'IS NULL'。 https://docs.djangoproject.com/en/dev/ref/models/querysets/#std:fieldlookup-isnull – dm03514 2013-02-20 21:01:41