2013-02-20 29 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