Django, the best, fastest way to get only the first and last item from something, Customer.objects.xxxx

Django, the best, fastest way to get only the first and last element from something, Customer.objects.xxxx such a filter, value_list or ...

+6
python django django-models
source share
3 answers

Probably the most pythonic way:

myset = Customer.objects.filter(<something>).order_by(<something>) first, last = myset[0], myset.reverse()[0] 
+10
source share

What is the best, fastest way to get only the first and last

We'll see.

 customers = Customer.objects.filter(**conditions) first = customers.order_by('id')[0] last = customers.latest('id') 

Of course, if you can come up with an SQL query for this, it can be executed using the raw() method.

 query = "<your query to get first and last>" Customer.objects.raw(query) 
+4
source share

I am not completely familiar with the django internals, but I would suggest that the fastest way to do this is:

 elements = Customer.objects.filter(<something>) first_element = elements[0] last_element = elements[-1] 
0
source share

All Articles