Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the first element and the last element using django , Location.objects.all()

Tags:

this is my code.

obj_list=Location.objects.all() first_element=obj_list[0] last_element=obj_list[-1] 

then,

return render_to_response(template_name, {         'first_element':first_element,         'last_element':last_element,     }) 

and in the template:

{{ first_element.terminal_id}} {{last_element.terminal_id}} 

but it show nothing ,

what can i do ,

thanks

like image 665
zjm1126 Avatar asked Mar 05 '11 08:03

zjm1126


People also ask

What does objects all () return in Django?

all() Returns a copy of the current QuerySet (or QuerySet subclass). This can be useful in situations where you might want to pass in either a model manager or a QuerySet and do further filtering on the result.

What is first () in Django?

In my last Django project, we had a set of helper functions that we used a lot. The most used was helpers. first, which takes a query set and returns the first element, or None if the query set was empty. Instead of writing this: try: object = MyModel.objects.get(key=value) except model.DoesNotExist: object = None.

How do I get latest data in Django?

You need to specify a field in latest(). eg. Or if your model's Meta specifies get_latest_by, you can leave off the field_name argument to earliest() or latest() . Django will use the field specified in get_latest_by by default.


1 Answers

Have a look at http://docs.djangoproject.com/en/dev/topics/db/queries/#limiting-querysets

Negative indexing (i.e. Entry.objects.all()[-1]) is not supported.

Try:

first_element = Location.objects.all()[0] last_element = Location.objects.all().reverse()[0] 

-- Update 8/6/17 --

Based on @MisterRios' comment,

As of 1.6 Django supports using .first() and .last() on querysets: first_element = Location.objects.first() last_element = Location.objects.last()

Refer: https://docs.djangoproject.com/en/1.7/ref/models/querysets/#django.db.models.query.QuerySet.first

like image 54
zsquare Avatar answered Oct 14 '22 15:10

zsquare