How to do SELECT MAX in Django?

后端 未结 3 2111
北海茫月
北海茫月 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: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
    

提交回复
热议问题