Skip to content

Instantly share code, notes, and snippets.

@odigity
Created September 3, 2022 23:44
Show Gist options
  • Save odigity/53bf47cca9a238a905c276760153838d to your computer and use it in GitHub Desktop.
Save odigity/53bf47cca9a238a905c276760153838d to your computer and use it in GitHub Desktop.
anyk and anyq queryset methods for Django
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