I get a queryset for a certain model and I'd like to get its complement, i.e. all instances of that model that are not in the aforementioned queryset.
How can I do that?
Short solution
qs = Model.objects.filter(...) # qs with objects to exclude
result = Model.objects.exclude(pk__in=qs.values_list('pk', flat=True))
More DRY solution
However, if you want to use the logic many times, I would suggest to encapsulate it in a method. Here is an example I personnaly used in a custom queryset:
class QuerysetUtils:
def get_queryset_complement(self, method):
return self.exclude(pk__in=method().values_list('pk', flat=True))
class ExpirableQueryset(QuerysetUtils, models.query.QuerySet):
def expired(self):
return self.filter(expiration__lte=timezone.now())
def unexpired(self):
return self.get_queryset_complement(self.expired)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With