How to do SELECT MAX in Django?

后端 未结 3 2099
北海茫月
北海茫月 2020-12-12 23:28

I have a list of objects how can I run a query to give the max value of a field:

I\'m using this code:

def get_best_argument(self):
    try:
                 


        
3条回答
  •  無奈伤痛
    2020-12-12 23:42

    I've tested this for my project, it finds the max/min in O(n) time:

    from django.db.models import Max
    
    # Find the maximum value of the rating and then get the record with that rating. 
    # Notice the double underscores in rating__max
    max_rating = App.objects.aggregate(Max('rating'))['rating__max']
    return App.objects.get(rating=max_rating)
    

    This is guaranteed to get you one of the maximum elements efficiently, rather than sorting the whole table and getting the top (around O(n*logn)).

提交回复
热议问题