문제

I want to get the last value of a column. How can I get it? A traslation to Django queryset of SELECT column_name FROM table_name ORDER BY id DESC LIMIT 1. This works fine in MySQL but I don't get to find the equivalent one in Django. Suggestions? Solutions?

Before, it was a queryset that generated a queryset like this: SELECT MAX(column_name) FROM table_name WHERE column_name_2 = x, but it took so long and I wanna change.

Thanks!

도움이 되었습니까?

해결책

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

다른 팁

The equivalent will be following:

YourModel.objects.order_by('column_name')[0]

See here for documentation.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top