On May 25, 8:19 am, doniyor <
doniyor....@googlemail.com> wrote:
> hey guys,
> i need to loop over the number of ids of objects in my db table and create
> accordingly the same number of html fields. how can i do it.. my effort is
> this:
> numberOfIds = Produkt.objects.count()
> i = 1;
> for i in range(0,numberOfIds):
> p = Produkt.objects.get(id=i)
> #lookup in db and create html input field depending on the #of
> ids.
> i=i+1
Django stuff set aside, the right way to iterate over a range in
Python is:
for i in range(0, x):
print i
> but it says: Produkt matching query does not exist. i know, obviously it is
> not right,
You can be sure it _is_ right. Or do you think that no one would have
spot a bug in one of the most used features of a years tested
library ?
> but how is it possible?
create table foo(id int primary key auto_increment, num integer not
null);
insert into foo(num) values(1);
insert into foo(num) values(2);
insert into foo(num) values(3);
insert into foo(num) values(4);
select * from foo order by id;
delete from foo where id=2;
insert into foo(num) values(2);
select * from foo order by id;
If you want a list (well, a ValueQuerySet in this case) of
Produkts.id, the right call is:
ids = Produkt.objects.values_list("id", flat=True)
But iterating over this only to retrieve each produkt in a loop is a
waste of time and resources - you're doing N+1 queries instead of
_one_ single query. See Kenneth's post for the appropriate solution.