4

我有一个表,其中包含有关 fieldmeasurement 的元数据,其中字段“startDate”的类型为日期时间。当没有可用信息时,该值可以为空。我想在这个字段上运行一些统计数据,并获得最小值和最大值(即所有记录中最旧的测量值)。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)
4

1 回答 1

4
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'))
于 2013-03-06T12:25:18.547 回答