Wednesday, January 30, 2019

Re: Limiting a SubQuery based on instance's OuterRef


Thank you for fast reply! I've tried to rewrite a query using RowNumber()...

inner_subquery = queryset.objects.filter(date__gte=today, day_type='working_day')
inner_subquery = inner_subquery.annotate(row_number=Window(expression=RowNumber(), order_by=F('number').asc()))
inner_subquery = inner_subquery.filter(pk=OuterRef('pk'))
inner_subquery = inner_subquery.values('row_number')[:1]

outer_subquery = queryset.objects.annotate(row_number=Subquery(inner_subquery))
outer_subquery = outer_subquery.filter(row_number=OuterRef('number'))
outer_subquery = outer_subquery.values('value')[:1]

queryset = queryset.annotate(result=Subquery(outer_subquery))

...but stumbled upon a following exception:

Expression contains mixed types. You must set output_field.

Am I doing something wrong?

You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to
To post to this group, send email to
Visit this group at
To view this discussion on the web visit
For more options, visit

No comments:

Post a Comment