V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
kingofvir
V2EX  ›  Django

django orm inner join 分组之后的数据

  •  
  •   kingofvir · 2021-05-30 20:20:15 +08:00 · 1760 次点击
    这是一个创建于 1055 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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")) 这样只能找到 每个菜系中价格最高的信息,不包含 菜名和材料. 如果 Dishes 能 inner join 查询出来的 cuisine 和 max_price 就可以了,但是用 orm 该怎么写??

    3 条回复    2021-06-01 09:33:12 +08:00
    im67
        1
    im67  
       2021-05-30 23:29:24 +08:00
    复杂查询直接用 SQL 原生语句,有个接口
    ytymf
        2
    ytymf  
       2021-05-31 09:22:13 +08:00
    同意楼上。原生搞定,像你这种 model 里没有定义外键关系的,orm 比较难搞。
    generated
        3
    generated  
       2021-06-01 09:33:12 +08:00
    # 查最高价格川菜
    Dishes.objects.filter(cuisine=0).order_by("-price").first()
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1404 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 17:23 · PVG 01:23 · LAX 10:23 · JFK 13:23
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.