[英]How do I use the Django ORM to query this many-to-many example?
I have the following models:我有以下型号:
class Author(models.Model):
author_name = models.CharField()
class Book(models.Model):
book_name = models.CharField()
class AuthorBook(models.Model):
author_id = models.ForeignKeyField(Author)
book_id = models.ForeignKeyField(Book)
With that being said, I'm trying to emulate this query using the Django ORM (select all of the books written by a specific author, noting that Authors can have many books and Books can have many Authors):话虽如此,我正在尝试使用 Django ORM 模拟此查询(选择特定作者写的所有书籍,注意作者可以有很多书,书籍可以有很多作者):
SELECT book_name
FROM authorbook, book
WHERE authorbook.author_id = 1
AND authorbook.book_id = book.id
I've readthis FAQ page on the Django website, but before I modify my model structure and remove AuthorBook, I was curious if I could emulate that query using the current structure.我已经在 Django 网站上阅读了这个 FAQ 页面,但是在我修改我的模型结构并删除 AuthorBook 之前,我很好奇我是否可以使用当前结构模拟该查询。
You should be able to do:你应该能够做到:
books = Book.objects.filter(authorbook__author_id=1)
to get a QuerySet of Book objects matching your author_id restriction.获取与您的 author_id 限制匹配的 Book 对象的 QuerySet。
The nice thing about Django is you can cook this up and play around with it in the shell. Django 的好处是您可以将其编写好并在 shell 中使用它。 You may also find http://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships to be useful.
您可能还会发现http://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships很有用。
"AuthorBook" seems not correctly modeled. “AuthorBook”似乎没有正确建模。
You should use a ManyToManyField
:您应该使用
ManyToManyField
:
class Book(models.Model):
name = models.CharField()
authors = models.ManyToManyField(Author)
Then you can do:然后你可以这样做:
books = Book.objects.filter(authors__id=1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.