views:

55

answers:

3

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

+3  A: 

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

Let us 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 to do this it could be executed using the raw() method.

query = "<your query to get first and last>"
Customer.objects.raw(query)
Manoj Govindan
You don't have to write query twice: myset = Customer.objects.filter(**conditions); first = myset.order_by('id')[0]; last = myset..latest('id')
Tomasz Wysocki
@Tomas: You are right of course. Corrected.
Manoj Govindan
A: 

I am not totally familiar with the inner workings of django but I would assume the fastest way to do this would be:

elements = Customer.objects.filter(<something>)
first_element = elements[0]
last_element = elements[-1]
Andrew Hubbs
@Andrew: `last_element = elements[-1]` will raise an error; negative indexing is not supported by Querysets. Which makes sense if you think of the SQL issued (using `LIMIT` clause)
Manoj Govindan
Defining first/last_element is also of course probably not necessary.
Andrew Hubbs
@Manoj you are totally right. Good catch.
Andrew Hubbs
+3  A: 

Probably most pythonic way:

myset = Customer.objects.filter(<something>).order_by(<something>)
first, last = myset[0], myset.reverse()[0]
Tomasz Wysocki
+1. Concise and yes, Pythonic.
Manoj Govindan