Skip to content

Instantly share code, notes, and snippets.

@joffilyfe
Created December 10, 2023 13:53
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 joffilyfe/c5eb1cf687e87aa6b6d177132356ff04 to your computer and use it in GitHub Desktop.
Save joffilyfe/c5eb1cf687e87aa6b6d177132356ff04 to your computer and use it in GitHub Desktop.
Implementation of Query Object using Django ORM and python meta classes
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