Django, What's the best ,faste开发者_运维知识库st way to get only first and last element from something, Customer.objects.xxxx such filter, value_list or ...
Probably most pythonic way:
myset = Customer.objects.filter(<something>).order_by(<something>)
first, last = myset[0], myset.reverse()[0]
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)
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]
精彩评论