Django 1.11 子查询用 .exclude 注释

问题描述 投票:0回答:1

在查询集中不可能排除吗?我总是收到这个错误:

ValueError: This queryset contains a reference to an outer query and may only be used in a subquery.

我想知道为什么它不起作用的代码部分:

 def get_queryset(self):
    return self.queryset.annotate(
        foo_count=Subquery(
            Foo.objects.exclude(code__hash=OuterRef('hash'))
            .values('code')
            .annotate(cnt=Count('pk'))
            .values('cnt'),
            output_field=IntegerField()
        ),
    )
python django subquery django-queryset django-1.11
1个回答
0
投票

刚发现对于该 Django 版本,无法使用

.exclude
~Q()
或否定
OuterRef()

在这里发现了类似的问题:https://code.djangoproject.com/ticket/30739

解决方法是从 self.queryset.annotate 获取

RAW SQL Query
并按照您需要的方式 reformat

这是一个对我有用的解决方案示例:

return self.queryset.annotate(
    device_count_behind = RawSQL('''SELECT (your query)...''', (), IntegerField()),
)
© www.soinside.com 2019 - 2024. All rights reserved.