我是django和SQL查询的新手。我正在尝试使用django进行一些注释。但无法获得结果
+-----------------------+-----------+---------------------+
| email | event | event_date |
|-----------------------+-----------+---------------------|
| hector@example.com | open | 2017-01-03 13:26:13 |
| hector@example.com | delivered | 2017-01-03 13:26:28 |
| hector@example.com | open | 2017-01-03 13:26:33 |
| hector@example.com | open | 2017-01-03 13:26:33 |
| tornedo@example.com | open | 2017-01-03 13:34:53 |
| tornedo@example.com | 1 | 2017-01-03 13:35:22 |
| tornedo@example.com | open | 2016-09-05 00:00:00 |
| tornedo@example.com | open | 2016-09-17 00:00:00 |
| sparrow@example.com | open | 2017-01-03 16:05:36 |
| tornedo@example.com | open | 2017-01-03 20:12:15 |
| hector@example.com | open | 2017-01-03 22:06:47 |
| sparrow@example.com | open | 2017-01-09 19:46:26 |
| sparrow@example.com | open | 2017-01-09 19:47:59 |
| sparrow@example.com | open | 2017-01-09 19:48:28 |
| sparrow@example.com | delivered | 2017-01-09 19:52:24 |
+-----------------------+-----------+---------------------+
我有一个这样的表格,其中包含电子邮件活动。我想找到最近开放的人,我也想知道发生的每件事。我希望结果与
完全一样 email | open | click | delivered | max_open_date
hector@example.com 4 <null> 1 2017-01-03 22:06:47
sparrow@example.com 3 <null> 1 2017-01-09 19:48:28
tornedo@example.com 4 1 <null> 2017-01-03 20:12:15
我的模特看起来:
class EmailEvent(models.Model):
event = models.TextField(blank=True, null=True)
email = models.TextField(blank=True, null=True)
event_date = models.DateTimeField(blank=True, null=True)
我尝试了以下代码。它给出了打开,点击,交付的正确计数,但给出了max_open_date的错误结果。但我不知道为什么
EmailEvent.objects.values('email').annotate(
max_open_date=Case(When(event='open', then=Max('event_date')))),
open=Sum(Case(When(event='open',then=1),output_field=IntegerField())),
click=Sum(Case(When(event='click',then=1),output_field=IntegerField())),
open=Sum(Case(When(event='open',then=1),output_field=IntegerField())),
delivered=Sum(Case(When(event='delivered',then=1),output_field=IntegerField())),
)
帮助我获得我想要的确切结果。对不起,我的英语不好。谢谢!
答案 0 :(得分:1)
我不使用django,但可能你需要这样的东西:
max_open_date=Max(Case(When(event='open', then='event_date')))