How to do SELECT MAX in Django?

后端 未结 3 2089
北海茫月
北海茫月 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)).

    0 讨论(0)
  • 2020-12-12 23:51

    See this. Your code would be something like the following:

    from django.db.models import Max
    # Generates a "SELECT MAX..." query
    Argument.objects.aggregate(Max('rating')) # {'rating__max': 5}
    

    You can also use this on existing querysets:

    from django.db.models import Max
    args = Argument.objects.filter(name='foo') # or whatever arbitrary queryset
    args.aggregate(Max('rating')) # {'rating__max': 5}
    

    If you need the model instance that contains this max value, then the code you posted is probably the best way to do it:

    arg = args.order_by('-rating')[0]
    

    Note that this will error if the queryset is empty, i.e. if no arguments match the query (because the [0] part will raise an IndexError). If you want to avoid that behavior and instead simply return None in that case, use .first():

    arg = args.order_by('-rating').first() # may return None
    
    0 讨论(0)
  • 2020-12-13 00:03

    Django also has the 'latest(field_name = None)' function that finds the latest (max. value) entry. It not only works with date fields but also with strings and integers.

    You can give the field name when calling that function:

    max_rated_entry = YourModel.objects.latest('rating')
    return max_rated_entry.details
    

    Or you can already give that field name in your models meta data:

    from django.db import models
    
    class YourModel(models.Model):
        #your class definition
        class Meta:
            get_latest_by = 'rating'
    

    Now you can call 'latest()' without any parameters:

    max_rated_entry = YourModel.objects.latest()
    return max_rated_entry.details
    
    0 讨论(0)
提交回复
热议问题