Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save viktorvillalobos/f7ce83651b8c3e6aa86e3ee138c8e38b to your computer and use it in GitHub Desktop.
Save viktorvillalobos/f7ce83651b8c3e6aa86e3ee138c8e38b to your computer and use it in GitHub Desktop.
Data Classes for Django QuerySet filters and exclutions proposal
from __future__ import annotations
from dataclasses import dataclass
from typing import Optional
class Model:
def __init__(self, name: str, age: int) -> None:
self.name = name
self.age = age
def filter(self, **kwargs):
return kwargs
def exclude(self, **kwargs):
return kwargs
@dataclass
class Filters:
name__icontains: Optional[str] = None
age__gt: Optional[int] = None
name__isnull: Optional[bool] = False
def to_dict(self):
return {
key: value
for key, value in self.__dict__.items()
if value is not None
}
@dataclass
class Exclutions(Filters):
pass
if __name__ == "__main__":
filters = Filters(name__icontains="V")
exclutions = Exclutions(age__gt=18)
model = Model(name="Viktor", age=20)
filter_expected_result = {
"name__icontains": "V",
}
exclutions_expected_result = {
"age__gt": 18,
}
assert 'age_gt' not in filters.to_dict()
assert 'name_isnull' not in filters.to_dict()
assert 'name_gt' not in exclutions.to_dict()
assert model.filter(**filters.to_dict()) == filter_expected_result
assert model.exclude(**exclutions.to_dict()) == exclutions_expected_result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment