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 sol开发者_StackOverflow社区ution comparable in efficiency?
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()
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()
精彩评论