Suppose I have a table in db with rows like this:
| ID | Foo |
|---|---|
| 19 | 1 |
| 20 | 1 |
| 38 | 2 |
| 44 | 1 |
| 50 | 2 |
| 61 | 1 |
I want to get max id (50 in this example) from queryset like this:
MyModel.objects.filter(foo=2).order_by('id').values_list('id')[:limit]
limit, of course, can be greater than total row number. I can do this by fetching all queryset, convert it to list and use the last item
list(MyModel.objects.filter(foo=2).order_by('id').values_list('id')[:limit])[-1]
but can I do this in database, without fetching entire queryset?
Raw sql solution is welcome too. DB is PostgreSQL.
Update:
I need max id of items inside limited set, not all table! For example if limit == 1 if will be 38, if limit == 2 it will be 50 and if limit == 500 it still will be 50.