I’m trying to create a listing page of all the questions posted that share the same type of tags a single user has used in their own questions. In other words, if a User has only posted questions about Python and OOP, they would only see questions that shared either one or both of those tags.
Upon trying to implement this, I tried to use the .union()
queryset to add the different filtered querysets together. However the following error is raised:
ORDER BY not allowed in subqueries of compound statements.
Is there another means of trying to overcome this error and getting the expected result that doesn’t use the .union()
queryset and adding the filtered QuerySets together?
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
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