【问题标题】:Django conditional annotation count with filter (many-to-many) follower/following table带有过滤器(多对多)追随者/下表的 Django 条件注释计数
【发布时间】:2016-09-24 10:41:07
【问题描述】:

这对我来说有点令人费解,所以我决定寻求帮助。

我所拥有的是一个标准用户模型和一个跟踪用户是否相互关注的表格,该表格具有from_userto_userfollowing 值。第一个是我的用户表的外键,第三个是布尔值。

我想要做的是能够覆盖 django admin 中的默认 get_queryset 方法,这样我就可以根据用户拥有的关注者数量进行排序。

我目前卡在实际注释追随者数量的地方,这可能是我遗漏的一些小东西,但这是我的代码:

def get_queryset(self, request):
    return AuthUser.objects.annotate(
        followers_count=Sum(
            Case(
                When(user_relations__from_user=1, user_relations__to_relation__following=True, then=1),
                default=0,
                output_field=IntegerField()
            )
        ))

错误的部分 - 我坚持使用 user_relations__from_user=1,它应该是当前正在评估的用户的 id。

我需要在所有条目的聚合中做的是我已经在 User 模型中的单个案例场景中做的事情:

@property
def num_followers(self):
    return UserRelations.objects.filter(from_user=self, following=True).count()

看起来很简单,但是注释时如何获得from_user=self

编辑:尝试使用 F user_relations__from_user_id__pk=F('id') 时添加堆栈跟踪

附加说明 - 我的 from_userto_user fk 字段实际上被命名为 from_user_idto_user_id - 希望这不会导致额外的混淆。对此感到抱歉。

Internal Server Error: /admin/pkm_user/authuser/
Traceback (most recent call last):
  File "/home/bastor/Work/pokemall-api/env/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/bastor/Work/pokemall-api/env/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 616, in wrapper
    return self.admin_site.admin_view(view)(*args, **kwargs)
  File "/home/bastor/Work/pokemall-api/env/local/lib/python2.7/site-packages/django/utils/decorators.py", line 110, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "/home/bastor/Work/pokemall-api/env/local/lib/python2.7/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
  File "/home/bastor/Work/pokemall-api/env/local/lib/python2.7/site-packages/django/contrib/admin/sites.py", line 233, in inner
    return view(request, *args, **kwargs)
  File "/home/bastor/Work/pokemall-api/env/local/lib/python2.7/site-packages/django/utils/decorators.py", line 34, in _wrapper
    return bound_func(*args, **kwargs)
  File "/home/bastor/Work/pokemall-api/env/local/lib/python2.7/site-packages/django/utils/decorators.py", line 110, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "/home/bastor/Work/pokemall-api/env/local/lib/python2.7/site-packages/django/utils/decorators.py", line 30, in bound_func
    return func.__get__(self, type(self))(*args2, **kwargs2)
  File "/home/bastor/Work/pokemall-api/env/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 1548, in changelist_view
    self.list_max_show_all, self.list_editable, self)
  File "/home/bastor/Work/pokemall-api/env/local/lib/python2.7/site-packages/django/contrib/admin/views/main.py", line 47, in __init__
    self.root_queryset = model_admin.get_queryset(request)
  File "/home/bastor/Work/pokemall-api/django/pkm_user/admin.py", line 65, in get_queryset
    output_field=IntegerField()
  File "/home/bastor/Work/pokemall-api/env/local/lib/python2.7/site-packages/django/db/models/query.py", line 794, in annotate
    obj.query.add_annotation(annotation, alias, is_summary=False)
  File "/home/bastor/Work/pokemall-api/env/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 977, in add_annotation
    summarize=is_summary)
  File "/home/bastor/Work/pokemall-api/env/local/lib/python2.7/site-packages/django/db/models/aggregates.py", line 20, in resolve_expression
    c = super(Aggregate, self).resolve_expression(query, allow_joins, reuse, summarize)
  File "/home/bastor/Work/pokemall-api/env/local/lib/python2.7/site-packages/django/db/models/expressions.py", line 491, in resolve_expression
    c.source_expressions[pos] = arg.resolve_expression(query, allow_joins, reuse, summarize, for_save)
  File "/home/bastor/Work/pokemall-api/env/local/lib/python2.7/site-packages/django/db/models/expressions.py", line 779, in resolve_expression
    c.cases[pos] = case.resolve_expression(query, allow_joins, reuse, summarize, for_save)
  File "/home/bastor/Work/pokemall-api/env/local/lib/python2.7/site-packages/django/db/models/expressions.py", line 713, in resolve_expression
    c.condition = c.condition.resolve_expression(query, allow_joins, reuse, summarize, False)
  File "/home/bastor/Work/pokemall-api/env/local/lib/python2.7/site-packages/django/db/models/query_utils.py", line 91, in resolve_expression
    clause, joins = query._add_q(self, reuse, allow_joins=allow_joins, split_subq=False)
  File "/home/bastor/Work/pokemall-api/env/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1332, in _add_q
    allow_joins=allow_joins, split_subq=split_subq,
  File "/home/bastor/Work/pokemall-api/env/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1194, in build_filter
    lookups, value)
  File "/home/bastor/Work/pokemall-api/env/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 1709, in get_lookup_constraint
    raise exceptions.FieldError('Relation fields do not support nested lookups')
FieldError: Relation fields do not support nested lookups

【问题讨论】:

    标签: python django annotations conditional


    【解决方案1】:

    我想你在找F expressions

    from django.db.models import F
    
    def get_queryset(self, request):
        return AuthUser.objects.annotate(
            followers_count=Sum(
                Case(
                    When(user_relations__to_relation__from_user__id=F('id'),
                         user_relations__to_relation__following=True, then=1),
                    default=0,
                    output_field=IntegerField()
                )
            ))
    

    【讨论】:

    • 您好!感谢您的快速回复和 F 信息!它真的很摇滚,是一种众所周知的东西。尽管按照您的描述使用它,但由于某种原因,我似乎收到了 Relation fields do not support nested lookups 错误。
    • 嗯。您可以将此错误的堆栈跟踪作为对您的问题的编辑发布吗?
    • 我已根据您对模型结构的反馈编辑了答案 - 希望这是正确的。
    • 哦,我真尴尬。我搞砸了关系应该是 user_relations__to_relation__from_user_id=F('id') 忘记了 to_relation 现在它没有给出任何错误,但注释似乎不正确。就像排序是错误的。不过,我会更多地玩弄 F() 。也许我仍然缺少一些相当明显的东西。非常感谢您的帮助! :)
    • 目前好像根本没有排序?您应该能够添加一个 order_by 子句来对结果进行排序。假设这就是您所说的排序。
    猜你喜欢
    • 2012-04-05
    • 2012-03-07
    • 1970-01-01
    • 2017-11-13
    • 2018-05-25
    • 2011-06-04
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    相关资源
    最近更新 更多