我有以下django模型
class Product(models.Model):
owner = models.ForeignKey(User)
class ProductCount(models.Model):
product = models.ForeignKey(Product)
date = models.DateTimeField(default=now, blank=True)
clicked = models.BooleanField(default=False)
我试图获取每个日期条目点击一个产品的次数。
我已经成功完成了以下代码,但显然它已经很长了
products = ProductCount.objects.filter(product__owner=owner)
for p in products:
p = p.product
for d in products.datetimes("date", "second"):
rs = ProductCount.objects.filter(product=p, date__year=d.year, date__month=d.month, date__day=d.day,
date__hour=d.hour, date__minute=d.minute)
display = rs.count()
clicked = rs.filter(clicked=True).count()
我用distinct
,annotate(Count())
尝试了很多东西,但我无法获得预期的输出
我想要一个输出,例如
[
{
"product_id": "XXX",
"dates": [
{
"2015-08-28T14:30:07": {
"clicked": "N",
"view": "M"
}
}
]
}
]
修改 感谢@Sayse的评论我的请求快了7倍
for p in products:
for d in p.productcount_set.datetimes("date", "second"):
rs = p.productcount_set.filter(date__year=d.year, date__month=d.month, date__day=d.day, date__hour=d.hour, date__minute=d.minute)
display = rs.count()
clicked = rs.filter(clicked=True).count()
我想知道我是否可以获得更高的速度,或者至少在同一请求中获得display
和clicked
值