[Django]-Django.admin.SimpleListFilter.queryset – return list?

3👍

It’s not optimal (will result in an extra SQL query), and I’d be looking for ways to move the comment.posted_by_guest() logic into SQL if possible (show the body of that method if you’d like help with that), but this ought to work:

def queryset(self, request, queryset):
    expected_value = self.value()
    excludes = []
    for comment in queryset:
        if comment.posted_by_guest() != expected_value:
            excludes.append(comment.id)
    return queryset.exclude(pk__in=excludes)

The Django admin filter API could do with some improvement!

👤jbg

2👍

The problem here is that Django is expecting a queryset and your code is providing a list. You can fix this by wrapping your comprehension in a set:

    def queryset(self, request, queryset):
        if self.value():
            return set(comment for comment in queryset if comment.posted_by_guest())
        elif not self.value():
            return set(comment for comment in queryset if not comment.posted_by_guest())

Leave a comment