过滤Django中的最新记录 [英] Filter latest record in Django

查看:24
本文介绍了过滤Django中的最新记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写我的第一个Django应用程序,该应用程序从其他应用程序获取消息并存储有关它们的报告.

Writing my first Django app that gets messages from other applications and stores reports about them.

由于以下逻辑,它的执行速度非常慢,我希望可以改进该逻辑,但我一直在努力寻找一种无循环的方法.

It is performing very slow due to the following logic that I hope can be improved but I'm struggling to find a way to do it with out a loop.

基本上,我只是尝试遍历所有应用程序(大约有500个独特的应用程序)并获取每个应用程序的最新报告.这是我的模型和功能:

Basically I'm just trying to go through all of the apps (there are about 500 unique ones) and get the latest report for each one. Here are my models and function:

class App(models.Model):
    app_name = models.CharField(max_length=200)
    host = models.CharField(max_length=50)

class Report(models.Model):
    app = models.ForeignKey(App)
    date = models.DateTimeField(auto_now_add=True)
    status = models.CharField(max_length=20)
    runtime = models.DecimalField(max_digits=13, decimal_places=2,blank=True,null=True)
    end_time = models.DateTimeField(blank=True,null=True)



def get_latest_report():
    """ Returns the latest report from each app """
    lset = set()
    ## get distinct app values
    for r in Report.objects.order_by().values_list('app_id').distinct():
        ## get latest report (by date) and push in to stack.
        lreport = Report.objects.filter(app_id=r).latest('date')
        lset.add(lreport.pk)
    ## Filter objects and return the latest runs
    return Report.objects.filter(pk__in = lset)

推荐答案

如果您不害怕对数据库中的每个应用程序执行查询,可以尝试以下方式:

If you're not afraid of executing a query for every app in your database you can try it this way:

def get_latest_report():
    """ Returns the latest report from each app """
    return [app.report_set.latest('date') for app in App.objects.all()]

这为数据库中的每个应用程序添加了一个查询,但是它确实具有表达能力,有时可维护性和可读性比性能更重要.

This adds a query for every app in your database, but is really expressive and sometimes maintainability and readability are more important than performance.

这篇关于过滤Django中的最新记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆