Last active
February 3, 2023 22:27
-
-
Save hellysmile/6337361 to your computer and use it in GitHub Desktop.
django repository pattern
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
from django.contrib.sites.models import Site | |
class Object(object): | |
def __init__(self, model, key): | |
self.model = model | |
self.key = key | |
def __call__(self, *args, **kwargs): | |
params = {} | |
params[self.key] = args[0] | |
return self.model.objects.get(**params) | |
class Repository(object): | |
def __init__(self, model): | |
self.model = model | |
def get_by_param(self, key): | |
return Object(self.model, key) | |
def __getattr__(self, key): | |
_key = key.replace('get_by_', '') | |
return self.get_by_param(_key) | |
SiteRepository = Repository(Site) | |
print SiteRepository.get_by_id(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The Repository class becomes huge and unmaintainable if we want to create multiple filters with pagination. Therefore, I believe this approach is not flexible and extensible.
Maybe this link is valuable:
https://lukeplant.me.uk/blog/posts/evolution-of-a-django-repository-pattern/