django过滤日期时间=无

时间:2013-03-06 12:14:34

标签: django aggregates

我有一个包含字段测量元数据的表,其中字段'startDate'的类型为datetime。没有信息时,该值可以为空。我想对这个字段运行一些统计数据,并获得最小值和最大值(即所有记录中可用的最旧测量值)。 Max没有问题,但是对于Min,聚合返回None(空字段中的值)。

所以我的想法是在运行聚合之前从查询集中过滤这些记录。我找不到怎么做。

我试过了

oldestdate = Measurement.object.filter(startDate__isNull=True).aggregate(Min('startDate'))['startDate__min']

知道什么是错的,或者怎么做?

编辑: 更多测试显示:

Measurement.objects.filter(startDate_isnull=True) -> only records with startDate = None
Measurement.objects.filter(startDate_isnull=False) -> all records, also the ones with startDate = None. 
Measurement.objects.exclude(startDate__isnull=False) -> only records with startDate = None
Measurement.objects.exclude(startDate__isnull=True) -> shows all records (also startDate == None)

1 个答案:

答案 0 :(得分:3)

oldestdate = Measurement.objects.filter(
    startDate__isnull=True).aggregate(min_date=Min('startDate'))

# or to make it small:

oldestdate = Measurement.objects.filter(startDate__isnull=True
    ).aggregate(min_date=Min('startDate'), max_date=Max('startDate'))