iterate through list

8 views
Skip to first unread message

Kai Kobschätzki

unread,
Feb 14, 2020, 8:14:06 AM2/14/20
to django...@googlegroups.com
Hi:

I want to do something with the content of a table. Problem is, that the
IDs are not continuous. I tried:

import .models from Journal

last = Journal.obejects.last()
last += 1
for i in range(last):
  try:
    data = Journal.objects.get(pk=i)
    doing something with this data
  except:
    pass

This solution runs but it seems not smart...

I need the try because there a gaps in the table, so I have got e.g.
element 1, element 3, element 8. If there is not an try/except the for
will crash. And I need the last +=1 otherwise the last element won't be
interpret.

Could anyone show me how I could improve it?

Thansk and Greetings

bengoshi



Roger Gammans

unread,
Feb 14, 2020, 8:16:31 AM2/14/20
to django...@googlegroups.com
Use:

for data in Journal.objects.all():
....

Kai Kobschätzki

unread,
Feb 14, 2020, 8:28:21 AM2/14/20
to django...@googlegroups.com
Hi Roger:

Thanks a lot! Such as easy :)

Greetings

bengoshi

Roger Gammans

unread,
Feb 14, 2020, 8:32:22 AM2/14/20
to django...@googlegroups.com
No problem,

It 's all explained here :
https://docs.djangoproject.com/en/3.0/ref/models/querysets/

Kai Kobschätzki

unread,
Feb 14, 2020, 8:35:13 AM2/14/20
to django...@googlegroups.com
Thanks for the tip, I will read it :)

Greetings

bengoshi
Reply all
Reply to author
Forward
0 new messages