我想编写一个通用函数,给定一个查询集,返回模型每一列的不同字段的数量。
我目前的功能是:
[queryset.aggregate(Count(x, distinct=True)) for x in [x.get_attname() for x in queryset.model._meta._fields()]]
然而,这相当 hacky/丑陋/不清楚。我想知道是否有更简单/更清晰的方法来做到这一点?
谢谢。
请您参考如下方法:
你可以通过more than one聚合到 .aggregate,因此您可以这样做以减少对数据库的调用。 下面的代码未经测试,只是为了让您了解我的意思。
args = [Count(x.get_attname(), distinct=True)) for x in queryset.model._meta._fields()]
queryset.aggregate(*args)
