django - django orm 内部连接组按数据
问题描述
class Dishes(models.Model):
""" 菜品"""
cuisine_list = ((0, '川菜'), (1, '粤菜'), (2, '徽菜'), (3, '湘菜'))
name = models.CharField('菜名', max_length=100)
material = models.TextField('材料')
cuisine = models.IntegerField('菜系', choices=cuisine_list)
price = models.IntegerField('价格')
def __str__(self):
return self.name
如何选择: 各菜系中最贵的菜品信息,包括菜名和食材
Dishes.objects.values('cuisine').annotate(max_price=Max("price"))
这样,我们只能找到每道菜中价格最高的信息,不包括菜名和食材。如果我们可以从内部连接中查询美食和 max_price 就可以了,但是我们应该在 ORM 中写什么呢?
解决方案
如果使用 Postgresql,您可以使用以下内容:
Dishes.objects.all().order_by().order_by(
'cuisine', # to group by this value
'-price' # descending by price will put highest first
).distinct('cuisine')
有关说明,请参阅https://docs.djangoproject.com/en/3.0/ref/models/querysets/#distinct。另请参阅https://www.semicolonworld.com/question/61934/django-group-by-one-field-only-take-the-latest-max-of-each-group-and-get-back-the- orm-objects以进一步讨论类似问题和此建议的来源。
体面的解释Distinct On
可在:https ://www.geekytidbits.com/postgres-distinct-on/
推荐阅读
- java - 针对不同用户的设计模式
- api - 使用 GCP API 网关的 Graphql 后端的 OpenAPI 配置?
- google-apps-script - 有没有我可以创建的谷歌脚本,所以我的电子表格中的每一行都会复制到一个新的单独的工作表中?
- python - 给出响应后如何继续执行函数?
- visual-studio - 在调试会话之间单独保留选项卡 (Visual Studio 2019)
- javascript - Puppeteer:转到页码
- react-native - react-native:在平面列表中加载图像时内存增加
- build - 构建 Azure Function 项目时构建挂起(在 GenerateFunctions 任务上挂起)
- javascript - 如何创建倒计时 html 文本 60 到 0 的倒计时
- python - 使用 Python 将最初是 json 的 avro 文件转换回 json