如何在Django 1.9中加入多个表?

时间:2016-04-27 21:32:07

标签: python django django-orm


我需要一些帮助。我的问题是我试图在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;

这是我的模特:

review / 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)

users / models.py

[用户]

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

顺便说一下,在我的文件 users / 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但是,我仍然无法做到这一点。任何帮助都会很感激。

1 个答案:

答案 0 :(得分:0)

最后我可以帮助解决问题。

我做的是下一个:

在我的文件 users / 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的帮助!