Fetch latest related objects in django

左心房为你撑大大i 提交于 2020-07-10 07:45:28

问题


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 best I have so far is the code below, but I'm thinking there must be a way to do this with less database queries?

def get_document_templates():
    result = []
    for d in Document.objects.filter(is_template=True).all():
        result.append(d.documentrevision_set.latest())
    return result

I've been investigating 'annotate' and 'aggregate' filters, but can't figure out how to do this more efficiently. I'd rather not get my hands dirty in raw SQL, as the database backend may be changing in the near future. Anyone have any ideas ?

thanks!!


回答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'))



回答2:


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

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


来源:https://stackoverflow.com/questions/18249830/fetch-latest-related-objects-in-django

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!