Skip to content Skip to sidebar Skip to footer

Fetch Latest Related Objects In Django

In my django app I have 'Documents'. Each document has one or more 'Revisions' that are ordered by date created. I'd like a way to get the latest revision for every document. The b

Solution 1:

I think there are two approaches. One explained this this blog post "Getting the related item in an aggregate". This will get you each Document with an attached 'Revision' (if you need access to both).

If you only want the Revision, you could try making use of the values() method. It's functionality changes subtly when used with aggregations:

As with the filter() clause, the order in which annotate() and values() clauses are applied to a query is significant. If the values() clause precedes the annotate(), the annotation will be computed using the grouping described by the values() clause.

However, if the annotate() clause precedes the values() clause, the annotations will be generated over the entire query set. In this case, the values() clause only constrains the fields that are generated on output.

So you could do a grouping of the Revision by Document and aggregate on date

Revision.objects.all().values('document').aggregate(Max('date'))

Solution 2:

you can fetch latest 9 data from a model like this:

Model.objects.all().order_by('-date')[0:9]

Post a Comment for "Fetch Latest Related Objects In Django"