带过滤器的 Django 条件注释计数(多对多)follower/following table

Django conditional annotation count with filter (many-to-many) follower/following table

这对我来说有点麻烦,所以我决定寻求帮助。

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

我想做的是能够覆盖 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。

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

@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

我想你在找 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()
            )
        ))