Skip to content

Instantly share code, notes, and snippets.

@hellysmile
Last active February 3, 2023 22:27
Show Gist options
  • Save hellysmile/6337361 to your computer and use it in GitHub Desktop.
Save hellysmile/6337361 to your computer and use it in GitHub Desktop.
django repository pattern
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)
@sepydev
Copy link

sepydev commented Feb 3, 2023

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/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment