我如何通过注释的Django中的串联来聚集字符串?
我在Django中有关注的模型:
class Click(models.Model):
url = models.ForeignKey(Url, on_delete=models.CASCADE)
browser = models.CharField(max_length=255)
platform = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
我想构建一个查询,以便在当月获得每天的总点击,以及浏览器和平台的串联。例如:
[
{
'created_at__day': 28,
'browsers': 'Chrome, Firefox',
'platforms': 'Windows, Linux',
'clicks': 4
}
]
直到这一刻,我做了什么:
queryset = Click.objects.filter(
url=url_instance,
created_at__month=datetime.now().month
).values('created_at__day', 'browser').annotate(
clicks=Count('created_at'),
)
我如何才能将每个浏览器和平台加以限制,只通过create_at__day进行分组?
I have the followed model in Django:
class Click(models.Model):
url = models.ForeignKey(Url, on_delete=models.CASCADE)
browser = models.CharField(max_length=255)
platform = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
I want to build a query to get the total clicks per day on the current month, along with browsers and platforms concatenated. For example:
[
{
'created_at__day': 28,
'browsers': 'Chrome, Firefox',
'platforms': 'Windows, Linux',
'clicks': 4
}
]
What I did until this moment was that query:
queryset = Click.objects.filter(
url=url_instance,
created_at__month=datetime.now().month
).values('created_at__day', 'browser').annotate(
clicks=Count('created_at'),
)
How can I concat every browser and platform, only grouping by created_at__day?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您很亲密,如@shabble所述,
StringAgg
如果您使用的是Postresql:如果不是,则必须使用
subquery
,并为数据库编写适当的字符串汇总
。我会像:我无法编写
youraggregation
,这取决于数据库中的可用内容。I think you're close, as @Shabble mentioned,
StringAgg
if you're using Postresql:If you're not, you'd have to go with a
Subquery
, and write an appropriate stringAggregation
for the database. I'd be something like:I cannot write
YourAggregation
, it'd depend on what's available on your database.目前尚不清楚您期望产生想要的结果的数据,但是如果您将PostgreSQL用作数据库,则 stringagg 或arrayagg可能是您想要的。
如果您想从聚合的字符串中排除重复项,则会更多地参与其中。
It's not clear exactly what data you have that you'd expect to produce the result you want, but if you're using Postgresql as your database, StringAgg or ArrayAgg might be what you're looking for.
It gets a bit more involved if you want to exclude duplicates from your aggregated strings though.