I need some help. My problem is that I'm trying to join multiple tables/models ((Question, Answer, User)) in Django 1.9 to get how many answers have a set of question made by a certain user.
I already have a sql query of what I want:
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;
And here are my models:
review/models.py
[Question]
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)
[Answer]
class Answer(models.Model):
question = models.ForeignKey(Question)
user = models.ForeignKey(User, db_index=True, null=True, blank=True)
users/models.py
[User]
class User(models.Model):
username = models.CharField(max_length=100, unique=True)
By the way, in my file users/views.py I have the next:
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')
but, I just get all the questions that the user has made.
I've been trying for a while looking for a way how to translate the query of above into the django-orm but, I still cannot accomplish that. Any help would be appreciate.