0

I have that kind of entries :

id  user  number
1  Peter  1
2  Jack   3
3  Kate   2
4  Carla  3

The name of my table is User so I would like to get only the user with the highest number but in some cases I don't know this number.

I thought to do something like that :

max_users = User.objects.filter(number=3)

But the problem is in that case I suppose I know that the highest number is 3 whereas it is not always the case. Could you help me please ?

Thank you very much !

  • 1
    Does this answer your question? [How to do SELECT MAX in Django?](https://stackoverflow.com/questions/844591/how-to-do-select-max-in-django) – Wouter Oct 11 '21 at 12:00
  • Not really because in the answer they explained how to sort by number, how to keep one of the highest number whereas I just want to filter and to keep only the highest value but it can contains many entries –  Oct 11 '21 at 12:20

1 Answers1

0

Try the following snippet:

from django.db.models import Max

max_number = User.objects.aggregate(Max('number'))['number__max']  # Returns the highest number.
max_users = User.objects.filter(number=max_number)  # Filter all users by this number.
Wouter
  • 534
  • 3
  • 14
  • 22