gpt4 book ai didi

Django在预取过滤相关模型上进行注释

转载 作者:行者123 更新时间:2023-12-03 10:36:21 24 4
gpt4 key购买 nike

我有一个 User 模型,每个 User 可以通过这个关系有很多 Post:

class Post(models.Model):
...
user = models.ForeignKey('User', related_name='posts')

,并且每个帖子都有一个like_count(整数字段),我想让用户(沿着他们的帖子)拥有超过 n 个帖子,并且被喜欢的次数超过 m 次,我这样做:
User.objects.prefetch_related(Prefetch('posts', queryset=Post.objects.filter(like_count__gte=m), to_attr='top_posts')).annotate(top_post_count=Count('top_posts')).filter(top_post_count__gte=n)

但是,我得到:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python3.4/dist-packages/django/db/models/query.py", line 912, in annotate
clone.query.add_annotation(annotation, alias, is_summary=False)
File "/usr/local/lib/python3.4/dist-packages/django/db/models/sql/query.py", line 971, in add_annotation
summarize=is_summary)
File "/usr/local/lib/python3.4/dist-packages/django/db/models/aggregates.py", line 19, in resolve_expression
c = super(Aggregate, self).resolve_expression(query, allow_joins, reuse, summarize)
File "/usr/local/lib/python3.4/dist-packages/django/db/models/expressions.py", line 513, in resolve_expression
c.source_expressions[pos] = arg.resolve_expression(query, allow_joins, reuse, summarize, for_save)
File "/usr/local/lib/python3.4/dist-packages/django/db/models/expressions.py", line 463, in resolve_expression
return query.resolve_ref(self.name, allow_joins, reuse, summarize)
File "/usr/local/lib/python3.4/dist-packages/django/db/models/sql/query.py", line 1462, in resolve_ref
self.get_initial_alias(), reuse)
File "/usr/local/lib/python3.4/dist-packages/django/db/models/sql/query.py", line 1402, in setup_joins
names, opts, allow_many, fail_on_missing=True)
File "/usr/local/lib/python3.4/dist-packages/django/db/models/sql/query.py", line 1327, in names_to_path
"Choices are: %s" % (name, ", ".join(available)))
django.core.exceptions.FieldError: Cannot resolve keyword 'top_posts' into field. Choices are: ...

最佳答案

docs解释它被分配给一个属性,根据 to_attr 命名参数,在 QuerySet 项上。

我不认为这意味着它可以作为模型字段访问,随后的注释可以链接到该模型字段。

您可能需要将其分为两个步骤。

编辑:该问题评论说可以链接过滤器,但不能链接注释。

关于Django在预取过滤相关模型上进行注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39354746/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com