在django中链接和过滤数据库查询的最佳方法是什么?

时间:2011-08-29 00:29:49

标签: django django-models django-queryset

# A Post Model
class Post(models.Model):
    title = model.CharField()
    user = models.ForeignKey(User)
    privacy = models.BooleanField() 

# query all post that have privacy = False, from a set of friends of type User.
# friends = [user1, user2, user5, user9]
def get_friend_posts(request):
    # Repeat the statement below for the size of friends. (4 here)
    friend_posts = Post.objects.filter(privacy=False).filter(user=fiends[0]) 
    variables = RequestContext(request, {
        'friend_posts' : friend_posts
    })
    return render_to_response('friends_page.html', variables)
  1. 进行此类数据库查询的最佳和最佳方式是什么?
  2. 另外,我如何追加query_set数据类型?在我的例子中,我需要运行 循环中的查询。 (我目前没有在代码中做)
  3. EDIT / UPDATE:

    posts_query = Posts.objects.filter(privacy=False)
    for friend in friends:
        q_list.append(bmks_query.filter(user=friend))
    
    for q in q_list:
        friend_posts += list(chain(q))
    

    对我的需求有更好的方法吗?

2 个答案:

答案 0 :(得分:2)

Django Querysets是懒惰的,因此在您尝试访问结果之前,它们不会进行评估。您可以像过滤那样链接过滤器,也可以将它们全部放在一起。我想这真的取决于你是否在开始时拥有所有信息,或者你是否需要根据某些东西动态添加过滤器。无论哪种方式,查询的最终结果都是相同的。查看关于主题的django的documentation

friends_posts = Post.objects.filter(privacy=False, user=friends[0])

friends_posts = Post.objects.filter(privacy=False).filter(user=friends[0])

第二部分。我想你只想要一个简单的'__in'过滤器,它会给你用户在朋友中的所有帖子。 (django's docs

friends_posts = Post.objects.filter(privacy=False, user__in=friends)

默认情况下,Django会让'friends'成为一个查询集本身,并在获取结果时执行子查询。如果您不想执行子查询,可以强制您的朋友找到一个列表,它会查询好友,然后查询帖子。

friends_posts = Post.objects.filter(privacy=False, user__in=list(friends))

答案 1 :(得分:0)

我想你可能正在寻找'__in' filter - 即:

def friend_posts(request):
    template = 'friends_page.html'

    friends = get_friends(request.user) # Gives you [user1, user2, user3] etc
    friend_posts = Post.objects.filter(privacy=False, author__in=friends)

    context = {'friend_posts': friend_posts}

    return render_to_response(template, context, RequestContext(request))
相关问题