How to do SELECT MAX in Django?

后端 未结 3 2112
北海茫月
北海茫月 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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
    

提交回复
热议问题