Skip to content

Instantly share code, notes, and snippets.

@lucasres
Created March 15, 2019 13:49
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 lucasres/1a5d9313081226a98d1e5c74541f7f09 to your computer and use it in GitHub Desktop.
Save lucasres/1a5d9313081226a98d1e5c74541f7f09 to your computer and use it in GitHub Desktop.
The clean repository from django application
#mixin for repository
class RepositoryMixin():
""" This class will served for base for all repository of project """
class Meta:
model = None
@classmethod
def all(cls):
"""
Shortcut for get all entity from model
return: QuerySet<Model>
"""
return cls.Meta.model.objects.all()
@classmethod
def get(cls,**kwargs):
"""
Shortcut for get method of model
return: Model
"""
return cls.Meta.model.objects.get(**kwargs)
@classmethod
def filter(cls, **kwargs):
"""
Shortcut for filter method of model
return: QuerySet<Model>
"""
return cls.Meta.model.objects.filter(**kwargs)
@classmethod
def create(cls,**kwargs):
"""
Shortcut for create method of model
return: Model
"""
return cls.Meta.model.objects.create(**kwargs)
#repository
# the logic of business
# exemple of buy one product
class ProductRepository(RepositoryMixin):
class Meta:
model = Product
@classmethod
def buy_product(cls,pk):
product = cls.get(pk=pk)
#have in stock
if product.amount > 0:
product.amount -= 1
product.save()
return 'Sold :)'
else:
raise Exception('Out of stock :(')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment