2016-04-27 3 views
0


私はいくつかの助けが必要です。私の問題は、複数のテーブル/モデル(質問、回答、ユーザ)をDjango 1.9に参加させようとしていることです。Django 1.9で複数のテーブルに参加するにはどうしたらいいですか?

私はすでに私が何をしたいのSQLクエリを持っている:

SELECT q.id, q.title, COUNT(a.id) AS total_answers 
FROM review_question AS q 
JOIN review_answer AS a ON q.id = a.question_id 
JOIN users_user AS u ON q.user_id = u.id 
WHERE q.user_id = 1 
GROUP BY q.id, q.title; 

そして、ここでは私のモデルは以下のとおりです。

レビュー/ models.py

[質問]

class Question(models.Model): 
    user = models.ForeignKey(User, db_index=True, null=True, blank=True) 
    tag = models.ManyToManyField(Tag) 
    title = models.CharField(max_length=200) 

[回答]

class Answer(models.Model): 
    question = models.ForeignKey(Question) 
    user = models.ForeignKey(User, db_index=True, null=True, blank=True) 

ユーザー/ models.py

私のファイルで、[ユーザー]

class User(models.Model): 
    username = models.CharField(max_length=100, unique=True) 

ところで、ユーザー/ views.py私は次を持っている:

class UserDetailView(DetailView): 
    model = User 

    def get_context_data(self, **kwargs): 
     # calling the get_context_data parent here 
     questions = Question.objects.filter(user = context['object']).order_by('created') 

ですが、ユーザーが作成したの質問が表示されます。

私は上記のクエリをdjango-ormに変換する方法を探していましたが、まだ達成できません。どんな助けでも感謝します。

+0

あなたは途中です。これであなたは 'Answer.objects.filter(question__in = questions)'という質問を得ました。これを確認してください:https://docs.djangoproject.com/es/1.9/ref/models/querysets/#in – MikeVelazco

+0

'Answer.objects.filter(question__user = user)'はどうですか?編集:あなたのクエリでGROUP BYに気づいていなかった、私の提案はそれをしません。 –

+0

@MikeVelazcoありがとう、私はそれをチェックし、私は何ができるかを参照してください;) –

答えて

0

最後に私の問題を助けることができました。私が何をしたか

は次だった:私のファイルユーザー/ views.pyで

class UserDetailView(DetailView): 
    model = User 

    def get_context_data(self, **kwargs): 
     # Calling the get_context_data parent 
     questions = Question.objects.filter(user = context['object']).order_by('created') 

     tags = [ question.tag.all() for question in questions ] 

     total_answers = self.get_total(questions) # Calling the function that return the total answer by question of a specific user 
     context['question_tags'] = zip(questions, tags, total_answers) #Zipping the lists with results to use it in the template 

     return context 

    def get_total(self, questions): 
     #Return the total answers that a question has (Here is the trick!) 
     return [ 
      Answer.objects.filter(question__id=question.id).annotate(num_answers=Count('question')).count() for question in questions] 

ターは、私がしたすべてでした。 最後に、@PauloAlmeidaと@MikeVelazcoに助けてくれたことに特に感謝したいと思います!

+1

リストの理解を使用する場合は、おそらく 'return [question.answer_set.count()を使って質問に回答する]'を行うことができます。 –

+0

はい、そうです。今見栄えが良い;)しかし、あなたはそれについて私に説明できますか?.answer_set.count() '私はそれをうまく理解しません。 –

+0

これは大丈夫です、私はすでにドキュメントで見つけました。そのようにするより良い方法のように見えます。ありがとうございました。 –

関連する問題