按字段中的值计算查询集中的对象。姜戈
Count objects in queryset by value in a field. Django
假设我有一个如下所示的模型:
class Car(models.Model):
TYPE_CHOICES = [
(1: 'Hatchback')
(2: 'Saloon')
type = models.CharField(choices=TYPE_CHOICES, ...)
color = models.CharField()
owner = models.ForeignKey(User, ...)
而且我想按特定值对对象进行计数。比如 Johns 拥有的黑色轿车或 Matts 拥有的白色掀背车。
到目前为止我想到的最好的是:
Car.objects.annotate(
black_saloons_owned_by_Johns=Count(
'type',
filter=(
Q(type=2) &
Q(owner__first_name='John')
)
),
white_hatchbacks_owned_by_Matts=Count(
'type',
filter=(
Q(type=1) &
Q(owner__first_name='Matt')
)
)
).aggregate(
aggregated_black_saloons_owned_by_Johns=Sum(
'black_saloons_owned_by_Johns'
),
aggregated_white_hatchbacks_owned_by_Matts=Sum(
'white_hatchbacks_owned_by_Matts'
)
)
有没有更好的方法可以得到想要的结果?谢谢
更新。
正如我所说,我需要在单个查询中执行多个查找。我使用的查询只有一个例子。我更新了它。应该明确指出。对不起。
我们可以过滤queryset,然后使用.count()
[Django-doc]:
Car.objects<strong>.filter(</strong>type=2, owner__first_name='John'<strong>).count()</strong>
或者如果需要进行多次查找,可以直接使用.aggregate(..)
:
您可以 Count
Car
对象直接使用:
Car.objects<strong>.aggregate(</strong>
total_john=Count(
'pk', <strong>filter=Q(type=2, owner__first_name='John')</strong>
),
total_matts=Count(
'pk', <strong>filter=Q(type=1, owner__first_name='Matt')</strong>
)
<strong>)</strong>
这将 return 一个有两个键的字典:'total_john'
和 'total_matts'
,它们将分别包含它们的 Car
数量的计数。
假设我有一个如下所示的模型:
class Car(models.Model):
TYPE_CHOICES = [
(1: 'Hatchback')
(2: 'Saloon')
type = models.CharField(choices=TYPE_CHOICES, ...)
color = models.CharField()
owner = models.ForeignKey(User, ...)
而且我想按特定值对对象进行计数。比如 Johns 拥有的黑色轿车或 Matts 拥有的白色掀背车。
到目前为止我想到的最好的是:
Car.objects.annotate(
black_saloons_owned_by_Johns=Count(
'type',
filter=(
Q(type=2) &
Q(owner__first_name='John')
)
),
white_hatchbacks_owned_by_Matts=Count(
'type',
filter=(
Q(type=1) &
Q(owner__first_name='Matt')
)
)
).aggregate(
aggregated_black_saloons_owned_by_Johns=Sum(
'black_saloons_owned_by_Johns'
),
aggregated_white_hatchbacks_owned_by_Matts=Sum(
'white_hatchbacks_owned_by_Matts'
)
)
有没有更好的方法可以得到想要的结果?谢谢
更新。
正如我所说,我需要在单个查询中执行多个查找。我使用的查询只有一个例子。我更新了它。应该明确指出。对不起。
我们可以过滤queryset,然后使用.count()
[Django-doc]:
Car.objects<strong>.filter(</strong>type=2, owner__first_name='John'<strong>).count()</strong>
或者如果需要进行多次查找,可以直接使用.aggregate(..)
:
您可以 Count
Car
对象直接使用:
Car.objects<strong>.aggregate(</strong>
total_john=Count(
'pk', <strong>filter=Q(type=2, owner__first_name='John')</strong>
),
total_matts=Count(
'pk', <strong>filter=Q(type=1, owner__first_name='Matt')</strong>
)
<strong>)</strong>
这将 return 一个有两个键的字典:'total_john'
和 'total_matts'
,它们将分别包含它们的 Car
数量的计数。