在我的模型中,我有Book
和Category
类定义如下:
class Category(models.Model):
name = models.CharField()
class Book(models.Model):
title = models.CharField()
categories = models.ManyToManyField(Category)
我想要的是Book
实例的给定查询集的categories
字段中引用的Category
实例集。
我意识到我可以遍历书籍的查询集并收集每本书的类别,但这对我来说似乎效率低下,因为这可以在单个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是正确的方法还是在效率上有更高级别的解决方案?
Edit:好吧,我没有一个ManyToManyField测试之前,所以我是猜测。新代码!
books = Book.objects.filter(title__contains="T")
categories = Category.objects.filter(book__in=books).distinct()
您需要根据'book'字段进行筛选:
book_ids = list(Book.objects.filter(...).values_list('id', flat=True)
categories_queryset = Category.objects.filter(book__in=book_ids).distinct()