basically i want to get the latest 30 log entries for every Host. Currently i’m doing this in django-piston.
def read(self,request):
val={}
for x in Host.objects.all():
val[x.uuid_id]=DataLog.objects.filter(host=x).order_by('-time')[:30]
return val
Unfortunately this request takes way to long (currently 1s for about 10k database entries).
Are there more efficient ways to do this?
Harper
If you are using PostgreSQL as a database backend and don’t need cross database compatibility, you can use the powerful window functions that allow something like that :
Imagine your table looks like that :
And you want the most recent value for each category. You will do :
You can use such a query in django via the
rawmethod on the query set manager :To get the last N entries by category, the query is a little more complicated and involves a subquery :
Seeing that, you could even make a view :
And create a django model that queries this view :
and query it “normally” :
Warning : again, don’t do this if you need a code that works on another database engine.