Created
December 10, 2023 13:53
-
-
Save joffilyfe/c5eb1cf687e87aa6b6d177132356ff04 to your computer and use it in GitHub Desktop.
Implementation of Query Object using Django ORM and python meta classes
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
import datetime | |
from django.utils import timezone | |
from polls import models | |
class Meta(type): | |
def __getattribute__(cls, name: str): | |
if name == "objects" and cls.MODEL: | |
return getattr(cls.MODEL, name) | |
return super().__getattribute__(name) | |
class BaseQuery(metaclass=Meta): | |
@classmethod | |
def by_pk(cls, pk: int): | |
return cls.MODEL.objects.get(pk=pk) | |
class QuestionQueries(BaseQuery): | |
MODEL = models.Question | |
@classmethod | |
def was_published_recently(cls): | |
return cls.MODEL.objects.filter( | |
pub_date__gte=timezone.now() - datetime.timedelta(days=10) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment