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
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.
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.
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.
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
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