2👍
Firstly, Django doesn’t let you filter after a slice, because in the underlying SQL, you can’t easily limit
the results and then filter with where
.
Doing the filtering then the slice probably not a problem anyway. Note that querysets are lazy, so Django will only ever fetch 120 objects from the db.
You’ll need to do some benchmarking to find out whether the exclude is really slowing you down. You could test whether the query with the exclude
and slice is noticeably slower than the query just with the slice.
If you find that the exclude is slow, you could filter in Python
comments = [c for c in comments if c.submitter_id not in condemned].
Note that you may end up with fewer than 120 comments this way.
Another option is to add a condemned
flag to the Submitter
model, then change the query to .exclude(submitter__condemned=True)
. This might be faster than the current .exclude(submitter_id__in=condemned)
.
You should also check that your database has indexes for the submitter_id
field. Since it’s a foreign key, it probably does.