开发者

How to get the next obj when looping in the django model

This is the code:

{% for o in page_obj.object_list %}
                <tr style="color:#4A3C8C;background-color:{% cycle '#E7E7FF' '#F7F7F7' %};"> 
                  <td align="center"> {{o.terminal_id}}</td>
                  <td align="center"> {{o.time_stamp}}</td> 
                  <td align="center" class="lat"> {{o.latitude|floatformat:"6"}}</td>
                  <td align="center" class="lng"> {{o.longitude|floatformat:"6"}}</td> 
                  <td align="center"> {{o.speed}}</td>
                  <td align="center"> 
                    <script>
                        $("sc开发者_如何学Goript").last().parent().parent()
                    </script>
                  </td>
                  <td align="center"> {{o.speed}}</td>
                  <td align="center"> {{o.adress_reality}}</td> 
                </tr> 
            {%endfor%}

I want to get the next object after 'o' object. How do I get the next from the 'o' object? Alternatively, how to get the next object in the python file that i can show this in the html as shown below?

{{ o.next_obj }}

thanks


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 %}


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):

class MyObj(models.Model):
    lat = ...
    lon = ...
    def get_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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜