通过使用 django orm 进行计数(*)来进行分组

Make group by having count(*) with django orm

以下型号:

class Day(models.Model):
    date = models.DateField(
        unique=True,
        null=False,
        blank=False,
    )


class Reservation(models.Model):
    user = models.ForeignKey(
        User,
        null=False,
        blank=False,
        related_name='reservations',
        verbose_name=_('Utilisateur'),
    )
    day = models.ForeignKey(
        Day,
        null=False,
        blank=False,
        related_name='reservations',
    )

要获取预订数量小于或等于 5 的天数,我会这样做:

SELECT day_id
FROM meal_reservation
GROUP BY day_id
HAVING count(*) <= 5

但是如何使用 Django ORM 来实现呢?

阅读有关使用 values+annotate 组合的文档,这就是您所需要的:

from django.db.models import Count

Reservation.objects.values('day').annotate(cnt=Count('id')).filter(cnt__lte=5)