我有一个模特:
class HistoricalRecord(models.Model):
history_id = models.CharField(max_length=32)
type = models.CharField(max_length=8)
history_date = models.DateField()
如何通过仅获取给定月份的最新对象(基于history_id)来获取每种HistoricalRecord
的计数。例如:
使用这些示例对象:
HistoricalRecord.objects.create(history_id="ABC1", type="A", history_date=date(2000, 10, 5))
HistoricalRecord.objects.create(history_id="ABC1", type="A", history_date=date(2000, 10, 27))
HistoricalRecord.objects.create(history_id="DEF1", type="A", history_date=date(2000, 10, 16))
HistoricalRecord.objects.create(history_id="ABC1", type="B", history_date=date(2000, 10, 8))
结果应为:
[
{
"type": "A",
"type_count": 2
},
{
"type": "B",
"type_count": 0
}
]
" A"是2是因为最新的HistoryRecord
对象有history_id" ABC1"是27日,类型是A;另一个是history_id" DEF1"。
我试过了:
HistoricalRecord.objects.filter(history_date__range(month_start, month_end)).order_by("type").values("type").annotate(type_count=Count("type"))
但显然这是不正确的,因为它获得了该月的所有值。结果的结构不必完全像上面那样,只要它清楚地传达每种类型的计数。
答案 0 :(得分:1)
这可以通过.extra()完成,将其添加到查询中:
.extra(
where=["""history_date = (SELECT MAX(history_date) FROM historical_record hr
WHERE hr.history_id = historical_record.history_id
AND hr.history_date < %s)"""],
params=[month_end]
)