【问题标题】:django aggregation and filtering resultdjango聚合和过滤结果
【发布时间】:2011-08-19 13:22:36
【问题描述】:

聚合后在 Django 中。
如果我在未聚合的列上使用 filter
我在 SQL 查询的 where 子句中使用它
而不是像预期的那样在having 中。

示例如下:

我有一张测试结果表。 假设我有 TestA 和 TestB。

Version:   2    |   2   |   2
TestA   :Pass   |Null   |Fail
testB   :Error  |Fail   |Null

每个测试都可以随时运行,
我想显示该测试的最新结果。

我尝试过的

x=Site.results.filter(timeEnd__isnull=False).values('idTest').annotate(Max('timeEnd'))

然后过滤 x 使用:

x.filter(result=<number of result>)

但我使用第二个过滤器得到的结果在原始 x 中看不到。

我怎样才能得到想要的结果?

但如果我尝试显示:

result(Version=2).failedFilter()
TestA=Fail
TestB=Fail

result(Version=2).PassedFilter()
TestA=Pass

result(Version=2).ErrorFilter()
TestB=Error

result(version=2)
TestA=Fail
TestB=Fail

实际上,除了失败的过滤器之外,其余的都需要为空。

总结:

tables:
test
----
    id
    name

Site
----
    id
    name

testresult
----------
    id
    date
    testid
    siteid
    result(int)

我想通过每次测试获得网站的最后结果 然后按结果过滤。

【问题讨论】:

  • 你的表没有意义。什么是 self.results?向我们展示您的 models.py,以便我们了解发生了什么
  • @airstrike ,它是对象的一部分,self 是 Site

标签: python mysql django filtering


【解决方案1】:

latest() 将返回查询集中的最新模型。

site = Site.objects.get(id=1)
for test in Test.objects.all():
        test_result = TestResult.objects.filter(site=site, test=test).latest('timeEnd')
        print test_result.result

annotate() 只是计算一个值,它不做任何过滤。我认为您当前的查询将返回任何设置了 timeEnd 的测试,而不仅仅是最后一个(我认为您想要的)。

【讨论】:

  • 我想收集所有的 test_result 迭代并过滤它们,另外,我有超过 100K 的测试
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-18
  • 2015-10-06
  • 2019-03-13
  • 2020-02-06
  • 2020-09-05
  • 2016-08-13
  • 2014-12-17
相关资源
最近更新 更多