class Post(models.Model): ... user = models.ForeignKey('User',related_name='posts')
,每个帖子都有一个like_count(整数字段),我希望得到的用户(沿着他们的帖子)有更多的帖子,这些帖子多被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,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,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在预取的过滤相关模型上进行注释全部内容,希望文章能够帮你解决Django在预取的过滤相关模型上进行注释所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)