Your problem is probably that a [-1]
index (which in python means "get the last item") doesn't work on querysets:
> YourModel.objects.order_by('id')[-1]
Traceback
...
AssertionError: Negative indexing is not supported.
The simple solution is to reverse the order and get the first one, which is exactly what you do in your hand-written SQL:
> YourModel.objects.order_by('-id')[0]
<YourModel....>
Putting a -
in front of a column name reverses the sort order. So that's probably the hint you need.
Since Django 1.6 there are special .first()
and .last()
methods on querysets, see Django's docs. It'd look like this for you:
> YourModel.objects.order_by('id').last()
<YourModel....>
Next up, you want to get just the value. Django has .values()
and .values_list()
for that. I often use .values_list('some single field', flat=True)
if I just want a list of single values. In your case:
> YourModel.objects.order_by('id').values_list('column_name',
flat=True).last()
1234
Of course, just grabbing the value from the object is shorter in this case:
> YourModel.objects.order_by('id').last().column_name
1234