【问题标题】:how to return number of distinct values django如何返回不同值的数量django
【发布时间】:2021-06-19 07:44:17
【问题描述】:

我正在为一家酒店做项目

family = 'family'
single = 'single'

room_types = (
    (family , 'family'),
    (single , 'single'),
)
class Room(models.Model):
    room_no = models.IntegerField(unique=True)
    beds = models.IntegerField(default=2)
    balcon = models.BooleanField(default=False)
    room_type = models.CharField(max_length=15,choices=room_types,default=single)

这是我的观点(查询)

lists = Room.objects.order_by().values('balcon ','beds','room_type').distinct().annotate(total=Count('beds',distinct=True)+Count('balcon',distinct=True)+Count('room_type',distinct=True))

我希望查询返回类似 beds: 4 , balcon : True , room_type : single , total : 10 beds: 3 , balcon : True , room_type : family, total : 4 等等 但它并没有像我预期的那样返回!是否可以根据几个字段进行分组并根据所选字段进行计数? 谢谢你的帮助..

【问题讨论】:

  • 我不太清楚什么你打算做什么。你到底算什么?如果有两个room_types,一个有一个balcon,另一个没有,那么结果应该是什么?
  • 在这种情况下:两个room_type都是family,但其中一个有balcon,另一个没有,我希望返回(家庭,真实:数量:1个房间)(家庭,假:数量:1个房间)
  • 我要返回数量(有特色的房间数量)
  • @WillemVanOnsem 请问有可能吗?

标签: python mysql django group-by


【解决方案1】:

您可以使用:

from django.db.models import Count

Room.objects.values('room_type', 'beds', 'balcon').annotate(
    total=Count('pk')
).order_by('room_type', 'beds', 'balcon')

这将提供一个字典查询集,如下所示:

<QuerySet [
    {'room_type' : 'family', 'beds': 3 , 'balcon' : True , 'total' : 4},
    {'room_type' : 'single', 'beds': 4 , 'balcon' : True, 'total' : 10}
]>

对于每个唯一值的组合,它会在名为'total' 的字典中添加一个额外元素,其中包含该类别的房间数。

【讨论】:

  • 谢谢,但返回错误号码total
  • @HunarMohammed: aaarrggghhhh...我打错了,是Count('pk'),不是Sum('pk'),否则我们是在总结主键。
  • 是的,非常感谢你,我希望你回答它,我碰巧你做到了,再次感谢你
  • 抱歉,我还有一个问题,我在 Room 模型中有另一个字段,名为 status:boolean field 我可以返回类似 'room_type' : 'single', 'beds': 4 , 'balcon' : True, 'total' : 10 , True status : 6 ,False status:4 的内容吗?我想返回该查询中的可用房间数,而不更改group by 显示该类别中有多少房间
  • @HunarMohammed:TrueFalse 状态究竟从何而来?如果房间被占用或不被占用,房间或其他物体似乎都在存储。模型中似乎没有任何东西可以确定这一点。我还建议提出一个新问题,这样可以让人们更轻松地搜索问题并获得相应的答案。
猜你喜欢
  • 2019-01-31
  • 2017-07-15
  • 2015-07-10
  • 2020-06-13
  • 2015-08-22
  • 1970-01-01
  • 2020-10-24
  • 2022-07-14
  • 1970-01-01
相关资源
最近更新 更多