如何使用 Django ORM 查询这个多对多示例?

发布于 2024-07-13 09:36:01 字数 665 浏览 9 评论 0原文

我有以下模型:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

鸩远一方 2024-07-20 09:36:01

您应该能够执行以下操作:

books = Book.objects.filter(authorbook__author_id=1)

获取与您的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:

books = Book.objects.filter(authorbook__author_id=1)

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.

慈悲佛祖 2024-07-20 09:36:01

“AuthorBook”似乎建模不正确。

您应该使用 ManyToManyField

class Book(models.Model):
  name = models.CharField()
  authors = models.ManyToManyField(Author)

然后您可以执行以下操作:

books = Book.objects.filter(authors__id=1)

"AuthorBook" seems not correctly modeled.

You should use a ManyToManyField:

class Book(models.Model):
  name = models.CharField()
  authors = models.ManyToManyField(Author)

Then you can do:

books = Book.objects.filter(authors__id=1)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文