Really basic question here but I was under the assumption that when we call model_name.objects.all()
the returned queryset can be thought of as a list since its iteratable you can slice throught it using python slice syntax. One of the first mistakes most new programmers make in any language is iterating over a list while deleting its elements, which of course does not produce the expected output. Eg:
ls = [i for i in range(10)]
for i in ls:
ls.remove(i)
print(ls)
will produce [1, 3, 5, 7, 9]
.
I assumed this would be the case with querysets as well but upon trying something like this:
for obj in my_model.objects.all():
if some_condition:
my_model.delete(obj)
I was surprised to find out it did in fact delete all the elements correctly. And if I removed the condition it deletes them all. I was expecting I’d have to do something like adding them to another list of objs_to_delete and then deleting them afterwards.
My question is: 1) Is it wrong to think of querysets as practically synonymous with lists then?
2) Although this seems possible, would it be bad practise to iterate over objects.all() and delete them since it reinforces a bad programming habbit when applied to normal lists?