与django orm一起计算和分组

时间:2016-11-06 17:06:15

标签: django

以下型号:

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',
    )

尝试做:

  

从meal_day.id =中选择* from meal_day left join meal_reservation   meal_reservation.day_id group by meal_day.id有计数(不同   meal_reservation.user_id)< = 1

我这样做:

Day.objects \
    .annotate(reserved_users_count=Count('reservations__user_id')) \
    .filter(reserved_users_count__lte=1)

但是这个查询会产生:

  

选择“meal_day”。“id”,“meal_day”。“日期”,   COUNT(“meal_reservation”。“user_id”)AS“reserved_users_count”FROM   “meal_day”LEFT OUTER JOIN“meal_reservation”ON(“meal_day”。“id”=   “meal_reservation”。“day_id”)GROUP BY“meal_day”。“id”,   “meal_day”。“date”具有COUNT(“meal_reservation”。“user_id”)< = 1   订购“meal_day”。“日期”ASC

如何制作想要的SQL查询?

0 个答案:

没有答案