django一對多查詢錯誤處理
阿新 • • 發佈:2019-01-26
今天試驗django級聯查詢的時候老是報錯:'QuerySet' object has no attribute 'user_answer_set'。
查了半天發現QuerySet就算是單條記錄,也是沒法進行級聯查詢的,必須要用單個model物件才行。
錯誤:
paper = User_Paper.objects.filter(id = 21)
answers = paper.user_answer_set.all()
正確:
paper = User_Paper.objects.get(id = 21)
answers = paper.user_answer_set.all()
model程式碼:
#使用者測試資訊 class User_Paper(models.Model): user_id = models.CharField(max_length=64) paper = models.ForeignKey(Paper) serialno = models.IntegerField() def __unicode__(self): return u'%s %s' % (self.user_id, self.paper)
#使用者測試答案資訊
class User_Answer(models.Model):
user_paper = models.ForeignKey(User_Paper)
question = models.ForeignKey(Question)
option = models.ForeignKey(Option)
def __unicode__(self):
return u'%s %s' % (self.question, self.option)