首页 > 解决方案 > 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 中写什么呢?

标签: django

解决方案


如果使用 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/


推荐阅读