python - 复合语句的子查询中不允许使用 ORDER BY;联合查询集
问题描述
我正在尝试为发布的所有问题创建一个列表页面,这些问题共享单个用户在他们自己的问题中使用的相同类型的标签。换句话说,如果用户只发布了有关 Python 和 OOP 的问题,他们将只会看到共享其中一个或两个标签的问题。
在尝试实现这一点时,我尝试使用查询.union()
集将不同的过滤查询集添加在一起。但是会引发以下错误:
ORDER BY not allowed in subqueries of compound statements.
我在这里发现了一个类似的问题,它提到了该方法可能与我正在使用的数据库 SQLite 不兼容:
错误“复合语句的子查询中不允许使用 ORDER BY”。在 django 中使用 Union 函数
是否有另一种方法可以尝试克服此错误并获得不使用查询集的预期结果.union()
?
模型.py
class Question(models.Model):
title = models.CharField(max_length=50)
body = models.TextField()
dated = models.DateField(default=date.today)
vote_tally = models.IntegerField(default=0)
user_account = models.ForeignKey(
'users.UserAccount',
on_delete=models.SET_NULL,
null=True, blank=True,
related_name="questions"
)
tags = models.ManyToManyField(Tag, related_name='questions')
objects = models.Manager()
dateranges = DateRangeQuerySet.as_manager()
status = QuestionStatusQuerySet.as_manager()
class Meta:
ordering = ['-dated']
default_manager_name = "objects"
def __str__(self):
return self.title
视图.py
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['lookup_buttons'] = {
'interesting': False,
'hot': False,
'week': False,
'month': False,
}
context['all_questions'] = Question.objects.all()
return context
def get(self, request):
context = self.get_context_data()
lookup = request.GET.get('tab', 'interesting')
if lookup not in context['lookup_buttons'].keys() or lookup == "interesting":
user_questions = (
Question.objects.filter(user_account_id=request.user.id)
.prefetch_related("tags")
)
user_tags = set(
[tag for question in user_questions
for tag in question.tags.all()]
)
qs = Question.objects.none()
tagged_querysets = []
for tag in user_tags:
qs = context['all_questions'].filter(tags__name=tag)
tagged_querysets.append(qs)
context['all_questions'] = Question.objects.all()
context['questions'] = qs.union([*tagged_querysets]) # error being raised here
解决方案
推荐阅读
- html - 为什么我在标题栏中的图像不起作用?
- python - Python3、PyAudio、7通道麦克风阵列数据
- python - 从另一个 .py 文件调用函数时的问题
- javascript - Kendo Grid 在 Grid 处于编辑模式时阻止编辑
- html - 如何使包含空格“”的所有单元格在html中成为黑色背景色
- javascript - 如何在动态添加中添加 TinyMCE 编辑器
- android - 调用需要 API 级别 21(当前最低为 19):android.view.View()
- python-3.x - FastAPI TypeError:“ModelMetaclass”类型的对象不是 JSON 可序列化的
- r - 创建具有重复模式 (R) 的矩阵
- python - 使用 python 在 Jupyter 实验室中找不到文件错误