2016-05-27 3 views
0

友達によって投稿質問のリストを取得する方法を、私は彼が次のユーザからの質問と回答のリストを取得し、ユーザーにログインする質問回答サイトを実装しようとしています。 私はdjango-friendshipを使ってユーザを実装しています。私は、現在のユーザーがフォローしているユーザーが投稿したすべての質問をどのように取り出すことができるかを知りたい。は、その後、ユーザー

私は次のことを試してみましたが、動作しません。

views.py

def index(request): 
    if request.session.get('current_user'): 
     questions = [] 
     users = Follow.objects.following(request.user) 
     i = 0 
     while i < len(users): 
      posts = Question.objects.filter(user=users[i]) 
      questions.append(posts) 
      i = i + 1 
     return render(request, "welcome/index.html",locals()) 

ここに私のテンプレートが

歓迎/ index.htmlを

{% extends "layout.html" %} 

{% block content %} 
    {% for q in questions %} 
     {{ q.title }} 
    {% endfor %} 

{% endblock %} 

答えて

0

テンプレート

{% extends "layout.html" %} 

{% block content %} 
    {% for q in questions %} 
     {{ q.title }} 
    {% endfor %} 

{% endblock %} 
+0

感謝の男

views.py

def index(request): if request.session.get('current_user'): users = Follow.objects.following(request.user) questions = Question.objects.filter(user__in=users) return render(request, "welcome/index.html",locals()) 

をループさせずにすべての質問を取得することができ、それが働きました。私は__inのことを知らなかった。どうもありがとう! – amankarn

0

postsだクエリセットです。したがって、questionsはクエリセットのリストであり、テンプレートではQuestionインスタンスを反復していませんが、title属性を持たないクエリセットはありません。あなたのビューで試すことができます。

questions.extend(posts) # not: append 

実際listQuestionのインスタンスを取得するために。それとも、あなたのテンプレートを変更することができます。

{% for qs in questions %} 
    {% for q in qs %} 
     {{ q.title }} 
    {% endfor %} 
{% endfor %}