Django QuerySet:为什么我无法过滤带注释的 QuerySet?
我正在尝试检索数据库中 100 种最受欢迎的书籍的列表,然后创建该列表中的唯一类别的列表。以下是我的简化书籍、收藏夹和类别模型:
class Book(models.Model):
name = models.CharField(max_length=100)
category = models.ForeignKey(Category)
class Favorite(models.Model):
user = models.ForeignKey(User)
book = models.ForeignKey(Book)
class Category(models.Model):
name = models.CharField(max_length=100)
我可以使用以下查询轻松获取 100 种最受欢迎的书籍的列表:
books = Book.objects.annotate(num_favorites=Count('favorite')).order_by('-num_favorites')[:100]
但是当我尝试获取这 100 种最流行的书籍的独特类别列表时,我开始遇到问题流行书籍。以下查询不起作用(下面发布了错误),我似乎无法弄清楚为什么。
>>> categories = Category.objects.filter(book__in=books).distinct()
>>> categories
FieldError: Cannot resolve keyword 'num_favorites' into field. Choices are: category, favorite, id, name
谁能告诉我我在这里缺少什么吗?
I'm trying to retrieve a list of the 100 most popular books in my db, and then create a list of unique categories that are in that list. Here are my simplified Book, Favorite, and Category models:
class Book(models.Model):
name = models.CharField(max_length=100)
category = models.ForeignKey(Category)
class Favorite(models.Model):
user = models.ForeignKey(User)
book = models.ForeignKey(Book)
class Category(models.Model):
name = models.CharField(max_length=100)
I can easily get a list of the 100 most popular books using the following query:
books = Book.objects.annotate(num_favorites=Count('favorite')).order_by('-num_favorites')[:100]
But where I start having problems is when I try to get a list of unique categories for those 100 most popular books. The following query does not work (error posted below) and I can't seem to figure out why.
>>> categories = Category.objects.filter(book__in=books).distinct()
>>> categories
FieldError: Cannot resolve keyword 'num_favorites' into field. Choices are: category, favorite, id, name
Can anyone shed some light on what I'm missing here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能会在一个查询中堆积太多内容。尝试拆分它:
You might be piling too many things into one query. Try splitting it: