首页 > 解决方案 > 复合语句的子查询中不允许使用 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

标签: pythondjango

解决方案


推荐阅读