簡體   English   中英

如何在Django 1.9中聯接多個表?

[英]How can I join multiple tables in Django 1.9?


我需要協助。 我的問題是我正在嘗試在Django 1.9中聯接多個表/模型((( Question,Answer,User )),以獲得某個用戶提出的一組問題中有多少個答案。

我已經有了想要的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)

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,但我仍然無法完成。 任何幫助將不勝感激。

最后,我可以解決我的問題。

接下來我要做的是:

在我的文件中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的幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM