Skip to content Skip to sidebar Skip to footer

How To Get The Next Obj When Looping In The Django Model

This is the code: {% for o in page_obj.object_list %}

Solution 1:

If you want to access multiple objects within a forloop, (although this is not a good design idea, but that is a separate discussion entirely.) you don't loop on the objects, but a counter and access the respective objects' counters moved around.

#In your view
obj_count = range(page_obj.object_list.count())

{% for i in obj_count %}

    o.i                   # Will access current object
    o.i+1                 # Will access the next object

{% endfor %}

Solution 2:

did you try to use get_next_by_FOO ? https://docs.djangoproject.com/en/1.2/ref/models/instances/#django.db.models.Model.get_next_by_FOO

If the field is not generated on the fly, you could add to your model (naively):

classMyObj(models.Model):
    lat = ...
    lon = ...
    defget_next_by_id(self):
        return self.objects.get(id=self.id+1)

And use {{ o.get_next_by_id.lat }}

Otherwise it is a good use for the templatetags, see the tag section but require more code. If you provide me a more detailed example of what you are doing i could try to give you a generic templatetag which might work in your case.

Good luck.

Post a Comment for "How To Get The Next Obj When Looping In The Django Model"