简体   繁体   English

找出一个Django查询

[英]Figure out one Django query

One Django ORM newbie question. 一个Django ORM新手问题。 I have the following models: 我有以下型号:

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)

How to get Book objects which questions' the user has answered? 如何获取用户回答了哪些问题的Book对象?

You can do it like this: 您可以这样做:

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

However you might consider that BookAnswered is basically just the linking table of a many-to-many relationship, and replace it completely with a ManyToManyField on BookQuestion pointing to User, in which case you can do this: 但是,您可能会认为BookAnswered基本上只是多对多关系的链接表,并将其完全替换为BookQuestion上指向User的ManyToManyField,在这种情况下,您可以这样做:

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

哦,找到了:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM