在 django 中執(zhí)行 JOIN 以反向關(guān)系獲取相關(guān)日期。共有三種型號(hào)。以下是模型的代碼class Question(models.Model): title = models.CharField(max_length=255 ) description = models.TextField(max_length=300) class Quiz(models.Model): name = models.CharField(max_length=225,blank=False ) quiz_type =models.IntegerField(choices=QUIZ_TYPE,default=0) questions = models.ManyToManyField( Question, through='QuestionQuiz', related_name="quiz_question") categories= models.ManyToManyField(Category,through='CategoryQuiz',related_name='quiz_category') class QuestionQuiz(models.Model): quiz = models.ForeignKey(Quiz,on_delete=models.CASCADE) question = models.ForeignKey(Question,on_delete=models.CASCADE) correct =models.DecimalField(max_digits=4, decimal_places=3) incorrect= models.DecimalField(max_digits=4, decimal_places=3) class Meta: unique_together = ('quiz','question')在此,使用模型問(wèn)題測(cè)驗(yàn)將問(wèn)題添加到測(cè)驗(yàn)中。這里, QuizQuestion 與問(wèn)題有外鍵關(guān)系。我需要從帶有特定 quiz_id 的 QuestionQuiz 中獲取所有問(wèn)題 JOIN 和記錄。假設(shè) quiz_id =3 那么我將獲取所有正確和不正確的問(wèn)題。如果該測(cè)驗(yàn) id 被添加到問(wèn)題中,那么它將顯示正確不正確,否則這些將是空白的。question_id | title|description|correct|incorrect|quesquizid
1 | Q1 |Q1desc |2 | -2 | 1
2 | Q2 |Q2desc | | |ques_id =1 添加到 quiz_id=3 .ques_id=2 未添加到 quiz_id=3。因此,正確不正確為空白。我嘗試了以下操作,但它會(huì)獲取所有問(wèn)題和相關(guān)的測(cè)驗(yàn)分?jǐn)?shù),而不管它們?cè)诋?dāng)前測(cè)驗(yàn)中是否出現(xiàn):Question.objects.prefetch_related('questionquiz_set').all()結(jié)果應(yīng)類似于以下查詢Select * from question as qs LEFT JOIN questionquiz as qq on (qq.question_id = qs.id AND qq.id=3)請(qǐng)檢查查詢結(jié)果:
在表 django 中執(zhí)行 JOIN
慕尼黑的夜晚無(wú)繁華
2022-10-11 15:12:43