V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
kingofvir
V2EX  ›  Django

django orm inner join 分组之后的数据

  •  
  •   kingofvir · May 30, 2021 · 2785 views
    This topic created in 1804 days ago, the information mentioned may be changed or developed.
    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 replies    2021-06-01 09:33:12 +08:00
    im67
        1
    im67  
       May 30, 2021
    复杂查询直接用 SQL 原生语句,有个接口
    ytymf
        2
    ytymf  
       May 31, 2021
    同意楼上。原生搞定,像你这种 model 里没有定义外键关系的,orm 比较难搞。
    generated
        3
    generated  
       Jun 1, 2021
    # 查最高价格川菜
    Dishes.objects.filter(cuisine=0).order_by("-price").first()
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3536 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 44ms · UTC 10:37 · PVG 18:37 · LAX 03:37 · JFK 06:37
    ♥ Do have faith in what you're doing.