Django, the best, fastest way to get only the first and last element from something, Customer.objects.xxxx such a filter, value_list or ...
Probably the most pythonic way:
myset = Customer.objects.filter(<something>).order_by(<something>) first, last = myset[0], myset.reverse()[0]
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.
raw()
query = "<your query to get first and last>" Customer.objects.raw(query)
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]