筛选查询结果而不启动新的SQL查询

时间:2017-09-08 12:31:55

标签: django

使用此代码我希望sql查询只能在'all_user_videos'上运行,后续过滤器会使用'all_user_videos'中存储的结果来进行过滤。

    # Get all user videos
    all_user_videos = Video.objects.filter( author = user )

    # User pending videos
    pending_videos = all_user_videos.filter( status = 'pending_review' )

    # Get user Video that need information
    info_required_videos = all_user_videos.filter( status = 'info_required' )

    # Get user video on sale
    on_sale_videos = all_user_videos.filter( status = 'on_sale' )

context = {
        "user_member_profile": instance,
        'pending_videos'     : pending_videos,
        'info_required'      : info_required_videos,
        'on_sale'            : on_sale_videos
    }

似乎并非如此,并且每个过滤器都运行查询。 我如何才能使pending_videos,info_required_videos和on_sale_videos不重新启动查询并使用'all_user_videos'中的查询结果?

1 个答案:

答案 0 :(得分:0)

您可以在查询中使用正则表达式。

all_user_videos = list(Video.objects.filter(author=user, status__regex=r'^(pending_review|info_required|on_sale)$'))
pending_videos = [i for i in all_user_videos if i.status == 'pending_review']

pending_videos = []
for i in all_user_videos:
    if i.status == 'pending_review':
        pending_videos.append(i)
    elif i.status == 'info_required':
       ...