Created
March 15, 2019 13:49
-
-
Save lucasres/1a5d9313081226a98d1e5c74541f7f09 to your computer and use it in GitHub Desktop.
The clean repository from django application
This file contains hidden or 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
#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