How to negate a queryset function in django?

I have this queryset in django 3.1

class AuthenticationQuerySet(InheritanceQuerySet):
    def expired(self):
        return self.filter(date_created__lt=timezone.localtime() - self.model.ACTIVE_THRESHOLD)

    def active(self):
        return self.filter(status__in=["PENDING"]).filter(
            date_created__gt=timezone.localtime() - self.model.ACTIVE_THRESHOLD
        )

Notice that in active function there is just negation from expired function in the second filter. I did it like this, because I could not figure out a more simple solution. But it feels like there should be a way to negate what a queryset function filters?

What I imagine and what feels much more natural is something like

class AuthenticationQuerySet(InheritanceQuerySet):
    def expired(self):
        return self.filter(date_created__lt=timezone.localtime() - self.model.ACTIVE_THRESHOLD)

    def active(self):
        return self.filter(status__in=["PENDING"]).not(self.excluded)

Is something like this possible?

or should I just go for something like:

class AuthenticationQuerySet(InheritanceQuerySet):
    def expired(self):
        return self.filter(self._expired_condition)
    
    def active(self):
        return self.filter(date_resolved__isnull=True, status__in=["PENDING"]).exclude(self._expired_condition)
    
    @property
    def _expired_condition(self):
        return Q(date_created__lt=timezone.localtime() - self.model.ACTIVE_THRESHOLD)

? but this seems just really ugly and hacky...

Thanks for suggestions!



Read more here: https://stackoverflow.com/questions/64407072/how-to-negate-a-queryset-function-in-django

Content Attribution

This content was originally published by Charlestone at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: