Created
October 1, 2024 13:11
-
-
Save Vashkatsi/aad558a27cb65796051aca2eef103b74 to your computer and use it in GitHub Desktop.
Python Repository
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 abc import ABC, abstractmethod | |
class AbstractRepository(ABC): | |
def __init__(self, model_class): | |
self.model_class = model_class | |
@abstractmethod | |
def get(self, **kwargs): | |
pass | |
@abstractmethod | |
def filter(self, **kwargs): | |
pass | |
@abstractmethod | |
def create(self, **kwargs): | |
pass | |
@abstractmethod | |
def update(self, instance, **kwargs): | |
pass | |
@abstractmethod | |
def delete(self, instance): | |
pass | |
class BaseRepository(AbstractRepository): | |
def get(self, **kwargs): | |
return self.model_class.objects.get(**kwargs) | |
def filter(self, **kwargs): | |
return self.model_class.objects.filter(**kwargs) | |
def create(self, **kwargs): | |
return self.model_class.objects.create(**kwargs) | |
def update(self, instance, **kwargs): | |
for attr, value in kwargs.items(): | |
setattr(instance, attr, value) | |
instance.save() | |
return instance | |
def delete(self, instance): | |
instance.delete() | |
class BookRepository(BaseRepository): | |
def __init__(self): | |
super().__init__(Book) | |
def get_books_published_after(self, year): | |
return self.model_class.objects.filter(publication_year__gt=year) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment