错误“复合语句的子查询中不允许 ORDER BY”。在 Django 中使用 Union 函数

KhA*_*Han 1 python django search django-views

“复合语句的子查询中不允许使用 ORDER BY。” 在 Django 中使用 Icontains 加入两个查询集时,当我加入第三个查询集时出现问题,例如带有一些特殊字符的 slug

我的观点;

    if len(query)>78:
        myposts = Blogpost.objects.none()
    else:
        post_title = Blogpost.objects.filter(title__icontains=query)
        posts_content = Blogpost.objects.filter(content__icontains=query)
        posts_overview= Blogpost.objects.filter(overview__icontains=query)
        myposts = post_title.union(posts_content, posts_overview)


    if myposts.count() == 0:
        messages.warning(request, "No search results found. Please enter again.")
    context = {'myposts': myposts,'query':query}
    return render(request, 'blog/search.html', context)```
Run Code Online (Sandbox Code Playgroud)

Ger*_*ers 6

我认为这是与 SQLite 相关的问题,它不支持某些 Django 操作。
我用 SQLite 和 Postgres 数据库测试了类似的代码,第一个会失败。所以我的回答只有在您使用 SQLite 时才有意义。
在文档中,您可以阅读此内容(没有更多详细信息。您需要检查 SQLite 文档以确认是否确实如此)

此外,结果 QuerySet 只允许 LIMIT、OFFSET、COUNT(*)、ORDER BY 和指定列(即切片、count()、order_by() 和 values()/values_list())。此外,数据库对组合查询中允许的操作进行了限制。例如,大多数数据库不允许在组合查询中使用 LIMIT 或 OFFSET。 https://devdocs.io/django~3.1/ref/models/querysets#django.db.models.query.QuerySet.difference

使用union(), intersection(), and difference()操作时似乎出现了问题。

两种可能的解决方案:

Q款

myposts = Blogpost.objects.filter(
    Q(title__icontains=query) | Q(content__icontains=query) | Q(content__icontains=query)
)
Run Code Online (Sandbox Code Playgroud)

values_list(不太漂亮)

    post_title_ids = list(Blogpost.objects.filter(title__icontains=query).values_list('id', flat=True))
    posts_content_ids = list(Blogpost.objects.filter(content__icontains=query).values_list('id', flat=True))
    posts_overview_ids = list(Blogpost.objects.filter(overview__icontains=query).values_list('id', flat=True))
    ids_list = post_title_ids + posts_content_ids + posts_overview_ids

    myposts = Blogpost.objects.filter(id__in=ids_list)
Run Code Online (Sandbox Code Playgroud)