Django QuerySet:为什么我无法过滤带注释的 QuerySet?

发布于 2024-11-29 08:06:36 字数 891 浏览 0 评论 0原文

我正在尝试检索数据库中 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 技术交流群。

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

发布评论

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

评论(1

好菇凉咱不稀罕他 2024-12-06 08:06:36

您可能会在一个查询中堆积太多内容。尝试拆分它:

book_ids = (Book.objects.annotate(num_favorites=Count('favorite'))
    .order_by('-num_favorites')[:100].values_list('id', flat=True))
categories = Category.objects.filter(book__in=book_ids).distinct()

You might be piling too many things into one query. Try splitting it:

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