Created
September 3, 2022 23:44
-
-
Save odigity/53bf47cca9a238a905c276760153838d to your computer and use it in GitHub Desktop.
anyk and anyq queryset methods for Django
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class FooQS(models.QuerySet): | |
# expects zero or more filter-style kwargs | |
def anyk(self, **kwargs): | |
if len(kwargs) == 0: | |
return self | |
if len(kwargs) == 1: | |
return self.filter(**kwargs) | |
q = Q(kwargs.popitem()) | |
for k, v in kwargs.items(): | |
q = (q | Q(**{k:v})) | |
return self.filter(q) | |
# expects zero or more Q objects | |
def anyq(self, *args): | |
if len(args) == 0: | |
return self | |
if len(args) == 1: | |
return self.filter(args[0]) | |
args = list(args) | |
q = args.pop(0) | |
for arg in args: | |
q = (q | arg) | |
return self.filter(q) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment