[英]Use django count or values_list counter, which is better?
I write a view for exporting data, my model is like this: 我写了一个导出数据的视图,我的模型是这样的:
class Event(models.Model):
KIND_CHOICES = (('doing', 'doing'),
('done', 'done'),
('cancel', 'cancel'))
created_at = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey('auth.User')
kind = models.CharField(max_length=20, choices=KIND_CHOICES)
Event is of one kind in three kinds, every user may has 3~10 events every month, firstly I query events of this month: 事件是三种中的一种,每个用户每月可能有3~10个事件,首先我查询本月的事件:
events_this_month = Event.objects.filter(created_at__year=2013,
created_at__month=5)
then find all the users: 然后找到所有用户:
users = User.objects.all()
I export data like this: 我导出这样的数据:
for user in users:
# 1000 users with 5 events each
user_events = events_this_month.filter(created_by=user)
doing_count = user_events.filter(kind='doing').count()
done_count = user_events.filter(kind='done').count()
cancel_count = user.events.filter(kind='cancel').count()
append_to_csv([user.username, doing_count, done_count, cancel_count])
Then I tried using collections.Counter
, I think this will cut down count SQL times(actually it decreases to 1200 from 3000+): 然后我尝试使用collections.Counter
,我认为这将减少计数SQL次数(实际上它从3000+减少到1200):
for user in users:
user_events = events_this_month.filter(created_by=user)
counter = Counter(user_events.values_list('kind', flat=True))
doing_count = counter['doing']
done_count = counter['done']
cancel_count = counter['cancel']
...
Which way is better ? 哪种方式更好 ?
Is where a more idiomatic way to count data like this more effciently ? 就是一个更地道的方式,更有效牙缝算这样的数据?
This is not tested but the idea is to group by user
and then group by kind
: 这不是测试,但这个想法是由一群user
,然后按组kind
:
from django.db.models import Count
events_this_month = Event.objects.values('created_by', 'kind') \
.filter(created_at__year=2013, created_at__month=5) \
.annotate(cc=Count('kind'))
Let me know if this works as i have not tested this. 让我知道这是否有效,因为我没有测试过这个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.