Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 543
vernomcrp Avatar asked Sep 08 '10 04:09

vernomcrp


People also ask

What is __ GTE in Django?

The gte lookup is used to get records that are larger than, or equal to, a specified value. For a greater than, but not or equal to, search, use the gt lookup.

How do I get last record in Django?

Django Doc: latest(field_name=None) returns the latest object in the table, by date, using the field_name provided as the date field. This is the neat way to do it. Also, "If your model's Meta specifies get_latest_by, you can leave off the field_name argument to latest()" as per the docs.

What does First () do in Django?

first, which takes a query set and returns the first element, or None if the query set was empty. Note, that this is not identical. The get method will ensure that there is exactly one row in the database that matches the query.

What is all () in Django?

The method all() on a manager just delegates to get_queryset() , as you can see in the Django source code: def all(self): return self.get_queryset() So it's just a way to get the QuerySet from the Manager. This can be handy to ensure that you're dealing with a QuerySet and not a Manager, because MyModel.


2 Answers

Probably most pythonic way:

myset = Customer.objects.filter(<something>).order_by(<something>)
first, last = myset[0], myset.reverse()[0]
like image 136
Tomasz Wysocki Avatar answered Sep 21 '22 06:09

Tomasz Wysocki


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)
like image 35
Manoj Govindan Avatar answered Sep 23 '22 06:09

Manoj Govindan