弄清楚一个Django查询

时间:2013-09-15 14:40:38

标签: python django

一个Django ORM新手问题。我有以下型号:

class Book(models.Model):
    title = models.CharField(max_length=100,null=True)

class BookQuestions(models.Model):
    video = models.ForeignKey(Book,null=True)

class BookAnswered(models.Model):
    answer = models.ForeignKey(BookQuestions, null=True)
    user = models.ForeignKey(User)

如何获取用户已回答问题的Book对象?

2 个答案:

答案 0 :(得分:0)

你可以这样做:

BookQuestion.objects.filter(bookanswered__user=request.user)

但是你可能会认为BookAnswered基本上只是多对多关系的链接表,并且用BookQuestion上指向User的ManyToManyField完全替换它,在这种情况下你可以这样做:

BookQuestion.objects.filter(user=request.user)

答案 1 :(得分:0)

哦,发现它:

Book.objects.filter(bookquestions__bookanswered__user=request.user)