Django, What's the best ,fastest way to get only first and last element from something, Customer.objects.xxxx such filter, value_list or ...
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With