2013-07-17 80 views
0

領域創建一個查詢我有使用兩種模式可以節省學生測驗的應用程序: StudentQuiz保存學生被要求 StudentQuestion節省了學生的每一個這些問題的反應的問題。如何基於另一個查詢集

class StudentQuestion(models.Model): 
    user = models.ForeignKey(User) 
    question = models.ForeignKey('Question') # comes from a Questions table 
    answer = models.CharField("Answer", max_length = 100, blank=True, null=True) 
    q_score = models.IntegerField("Score", blank=True, null=True) 


class StudentQuiz(models.Model): 
    user = models.ForeignKey(User) 
    date = models.DateField("Quiz Date", blank=True, null=True) 
    total_score = models.IntegerField("Score", blank=True, null=True) 
    ques1 = models.ForeignKey(StudentQuestion, related_name='q1') 
    ques2 = models.ForeignKey(StudentQuestion, related_name='q2') 
    ques3 = models.ForeignKey(StudentQuestion, related_name='q3') 
    ques4 = models.ForeignKey(StudentQuestion, related_name='q4') 
    ques5 = models.ForeignKey(StudentQuestion, related_name='q5') 

我想找到問題的學生參加了爲他獲得了得分的,比如某個日期範圍內的數量,1

所以我創建第一個查詢集:

quizzes_done = StudentQuiz(user=mystudent, date__gte=start_date, date__lte=end_date) 

現在,我想看看是在這些StudentQuizzes,並要計算有q_score = 1問題數的所有問題。

目前,我只是遍歷的查詢集和編程這樣做。但是QuerySet可能很大。

有沒有辦法做到這一點使用Django的數據庫API的?

回答

2

看看該文檔上queries that span relationships

基本上,你應該能夠引用您的StudentQuestion對象上StudentQestion查詢相關的student_quiz,上q_score和用戶過濾,然後用__訪問你想要的StudentQuiz屬性(例如filter(student_quiz__date_gte=blah

+0

我一直在嘗試你的建議,但還沒有得到它。我有一個StudentQuizzes的QuerySet。每個StudentQuiz有5個FK到StudentQuestion。 StudentQuestion沒有FK給StudentQuiz。所以我無法過濾StudentQuestion並查找student_quiz__date_gte = blah - 對嗎? – zaphod

+0

你其實可以!從文檔「這倒過來了。要引用‘反向’的關係,只是使用模型的小寫名字。」如果你看看你的例子,它與你的設置很相似 - Blog to Entry是一對多的關係,其中條目具有博客的外鍵。 https://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships是該頁面上的另一個很好的部分(儘管如果我是你,我可能會從頭開始閱讀) – Colleen

+0

I確實讀到了相反的關係。我沒有得到所有的條目。我想我可能出錯的部分是同一個模型中有5個FK。所以可能只是使用型號名稱是不夠的? – zaphod

相關問題