#How can I annotate more than one result from a Subquery?

3 messages · Page 1 of 1 (latest)

jade cairn
#

I have the following query:

export_date_query = RecordExport.objects.filter(record=OuterRef("id")).order_by("-id").values("export__created_at")[:1]
return Record.objects.annotate(export_date=Subquery(export_date_query))

However, I would like to change it so that I return the latest TWO, but I get the error: "more than one row returned by a subquery used as an expression". Is there a straightforward way to achieve this? Thanks!

amber fern
#

The above shouldn't cause that error because it has a slice. Can you please double check your code?

jade cairn
#

Hey @amber fern, sorry for the confusion - the current code works. I meant the latest two, so the slice would be [:2], which would raise the error mentioned before.