【发布时间】:2018-01-17 09:02:08
【问题描述】:
在一个 Django 项目中,我定义了这些简化模型:
class People(models.Model):
name = models.CharField(max_length=96)
class Event(models.Model):
name = models.CharField(verbose_name='Nom', max_length=96)
date_start = models.DateField()
date_end = models.DateField()
participants = models.ManyToManyField(to='People', through='Participation')
class Participation(models.Model):
"""Represent the participation of 1 people to 1 event, with information about arrival date and departure date"""
people = models.ForeignKey(to=People, on_delete=models.CASCADE)
event = models.ForeignKey(to=Event, on_delete=models.CASCADE)
arrival_d = models.DateField(blank=True, null=True)
departure_d = models.DateField(blank=True, null=True)
现在,我需要生成一个参与图:对于每个活动日,我想要相应的参与总数。 目前,我使用这个糟糕的代码:
def daterange(start, end, include_last_day=False):
"""Return a generator for each date between start and end"""
days = int((end - start).days)
if include_last_day:
days += 1
for n in range(days):
yield start + timedelta(n)
class ParticipationGraph(DetailView):
template_name = 'events/participation_graph.html'
model = Event
def get_context_data(self, **kwargs):
labels = []
data = []
for d in daterange(self.object.date_start, self.object.date_end):
labels.append(formats.date_format(d, 'd/m/Y'))
total_participation = self.object.participation_set
.filter(arrival_d__lte=d, departure_d__gte=d).count()
data.append(total_participation)
kwargs.update({
'labels': labels,
'data': data,
})
return super(ParticipationGraph, self).get_context_data(**kwargs)
显然,我在Event.date_start 和Event.date_end 之间每天运行一个新的SQL 查询。 有没有办法通过减少 SQL 查询的数量(理想情况下,只有一个)获得相同的结果?
我尝试了许多来自 Django orm 的聚合工具(values()、distinct() 等),但我总是遇到同样的问题:我没有包含简单日期值的字段,我只有 start 和结束日期(在事件中)和出发和到达日期(在参与中),所以我找不到按日期对结果分组的方法。
【问题讨论】:
-
也许你也应该用
python标记你的问题。那会引起更多的关注。此外,django-orm似乎比orm更合适。 -
谢谢,我已经按照你的建议做了
标签: python django performance django-orm