[Django]-How can you exclude an item in the query set while in a for loop?

6👍

Change the last portion of your code like this:

for a in results:

### code ###

    results = results.exclude(id=a.id)

since queryset.exclude() returns a new queryset, without changing the existing.

2👍

But you would do database query for each loop though since you calling .exclude() with each loop

If you just want to remove object for each loop, you could use:

new_list = list(results)
for a in results:  
    ### code ###
    new_list.remove(a)

Leave a comment