Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Getting complement of queryset

Tags:

python

orm

django

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?

like image 743
Ram Rachum Avatar asked Jan 11 '12 13:01

Ram Rachum


1 Answers

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)
like image 89
Bernhard Vallant Avatar answered Sep 20 '22 19:09

Bernhard Vallant