Django 中对象子集的 ManyToManyField 中的不同值

发布于 2024-11-29 05:33:17 字数 715 浏览 0 评论 0 原文

在我的模型中,我的类 BookCategory 定义如下:

class Category(models.Model):
    name = models.CharField()

class Book(models.Model):
    title = models.CharField()
    categories = models.ManyToManyField(Category)

我想要的是 Category 实例中引用的一组 Category 实例。给定 Book 实例查询集的 code>categories 字段。

我意识到我可以迭代书籍的查询集并收集每本书的类别,但这对我来说似乎效率低下,因为这可以在单个 SQL 查询中说明:

SELECT DISTINCT name
FROM myapp_book_categorys JOIN myapp_category ON myapp_book_categorys.category_id=myapp_category.id
WHERE myapp_book_categorys.book_id IN 
    (SELECT id FROM myapp_book WHERE ...);

原始 SQL 是正确的方法还是有更高级别的解决方案效率可比吗?

In my models I have the classes Book and Category defined like this:

class Category(models.Model):
    name = models.CharField()

class Book(models.Model):
    title = models.CharField()
    categories = models.ManyToManyField(Category)

What I want is the set of Category instances that are referenced in the categories field of a given queryset of Book instances.

I realize I can iterate through the queryset of books and gather the categories for each book but this seems inefficient to me as this could be stated in a single SQL query:

SELECT DISTINCT name
FROM myapp_book_categorys JOIN myapp_category ON myapp_book_categorys.category_id=myapp_category.id
WHERE myapp_book_categorys.book_id IN 
    (SELECT id FROM myapp_book WHERE ...);

Is the raw SQL the right way to go or there is a higher level solution comparable in efficiency?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

夜声 2024-12-06 05:33:17

编辑:好的,我没有 ManyToManyField 之前进行测试,所以我猜测。新代码!

books = Book.objects.filter(title__contains="T")
categories = Category.objects.filter(book__in=books).distinct()

Edit: Okay, I didn't have a ManyToManyField to test on before so I was guessing. New code!

books = Book.objects.filter(title__contains="T")
categories = Category.objects.filter(book__in=books).distinct()
以往的大感动 2024-12-06 05:33:17

您需要按“书籍”字段进行过滤:

book_ids = list(Book.objects.filter(...).values_list('id', flat=True)
categories_queryset = Category.objects.filter(book__in=book_ids).distinct()

You need to filter by the 'book' field:

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