Django, What's the best ,fastest way to get only first and last element from something, Customer.objects.xxxx such filter, value_list or ...
views:
55answers:
3
+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
2010-09-08 05:51:53
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
2010-09-08 06:44:34
@Tomas: You are right of course. Corrected.
Manoj Govindan
2010-09-08 06:57:46
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
2010-09-08 06:59:08
@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
2010-09-08 06:59:50
Defining first/last_element is also of course probably not necessary.
Andrew Hubbs
2010-09-08 07:00:31
+3
A:
Probably most pythonic way:
myset = Customer.objects.filter(<something>).order_by(<something>)
first, last = myset[0], myset.reverse()[0]
Tomasz Wysocki
2010-09-08 08:24:29