0

I'm have a django query with annotate and prefetch_related.

all_questions = Question.objects.all().annotate(is_complete=Case(
                When(
                    pk__in=completed_questions.values('pk'), 
                    then=Value(True)
                ),
                default=Value(False), 
                output_field=BooleanField()),
                votes_difference=Count('like')-Count('unlike'),
            ).order_by('votes_difference').prefetch_related('tags')

I want to limit the result to, let's say 100 objects.

I tried this query:

all_questions = Question.objects.all().annotate(is_complete=Case(
                When(
                    pk__in=completed_questions.values('pk'), 
                    then=Value(True)
                ),
                default=Value(False), 
                output_field=BooleanField()),
                votes_difference=Count('like')-Count('unlike'),
            ).order_by('votes_difference')[100].prefetch_related('tags')

I got this error message:

'Question' object has no attribute 'prefetch_related'

I checked the official documentation but can't seem to find any example related to it. Is it possible to do so?

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
Gagan
  • 367
  • 1
  • 4
  • 18
  • just push [100] after the prefech_related – Waldemar Podsiadło Jul 16 '22 at 07:20
  • @WaldemarPodsiadło i already tried that, it gives `object of type 'Question' has no len()` error – Gagan Jul 16 '22 at 08:47
  • It's strange error. I just try it on some of my classes and it works with annotate and order_by and prefetch_related. Limiting result should not interfere with queryset. oh by the way if you want only 100 results it should be [:100]. show your models – Waldemar Podsiadło Jul 16 '22 at 10:13

0 Answers0