通过django orm计数(*)来制作组

时间:2016-11-06 18:03:19

标签: django 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做到这一点?

1 个答案:

答案 0 :(得分:6)

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

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