我有两个模型如下:
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=20, verbose_name="Name")
def __str__(self):
return self.name
class Event(models.Model):
category = models.ForeignKey(Category, related_name="events", on_delete=models.CASCADE, verbose_name="Category")
started_at = models.DateTimeField(verbose_name="Started at")
ended_at = models.DateTimeField(null=True, blank=True, verbose_name="Ended at")
name = models.CharField(max_length=20, verbose_name="Name")
def __str__(self):
return self.name
我试图获得一个类别的特定时间段(如上个月)的总事件持续时间。
我可以得到总数(没有指定时间段)这样的持续时间:
from datetime import timedelta
from django.db import models
from django.db.modals.functions import Coalesce
from django.utils.timezone import now
Category.objects \
.filter(id=1) \
.annotate(
events_duration=Coalesce(
models.Sum(
Coalesce(models.F('events__ended_at'), now()) - models.F('events__started_at'),
),
models.Value(timedelta()),
),
)
但正如我所说,我希望在这个月和活动持续时间之间得到交集。它可行吗?
答案 0 :(得分:0)
试试这个
from datetime import datetime, timedelta
from django.db.models import Sum, F, DurationField
start_time = datetime.now() - timedelta(days=30)
end_time = datetime.now()
Event.objects.filter(started_at__gte=start_time, ended_at__lte=end_time, other_filter).annotate(
time_diff=F('ended_at') - F('started_at')).aggregate(sum_time_diff=Sum('time_diff', output_field=DurationField()))