如何使用 Django ORM 查询这个多对多示例?
我有以下模型:
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)
话虽这么说,我正在尝试使用 Django ORM 模拟此查询(选择特定作者撰写的所有书籍,请注意作者可以有很多书籍,书籍可以有很多作者):
SELECT book_name
FROM authorbook, book
WHERE authorbook.author_id = 1
AND authorbook.book_id = book.id
我已阅读 Django 网站上的此常见问题解答页面,但在修改模型之前结构并删除 AuthorBook,我很好奇是否可以使用当前结构模拟该查询。
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):
SELECT book_name
FROM authorbook, book
WHERE authorbook.author_id = 1
AND authorbook.book_id = book.id
I've read this 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该能够执行以下操作:
获取与您的author_id 限制匹配的Book 对象的QuerySet。
Django 的好处是您可以将其编写出来并在 shell 中使用它。 您可能还会发现
http://docs.djangoproject.com/ en/dev/topics/db/queries/#spanning-multi-valued-relationships
变得有用。
You should be able to do:
to get a QuerySet of Book objects matching your author_id restriction.
The nice thing about Django is you can cook this up and play around with it in the shell. You may also find
http://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships
to be useful.
“AuthorBook”似乎建模不正确。
您应该使用
ManyToManyField
:然后您可以执行以下操作:
"AuthorBook" seems not correctly modeled.
You should use a
ManyToManyField
:Then you can do: