I tried something like named_scope in RubyOnRails with Django
from django.db.models.query import QuerySet
from django.db import models
class PlayerScopeMixin(object):
"""
Player Class Scope Chain Mixin
"""
@property
def newcomer_time(self):
"""
:return:Start time of new player period(One week ago from now)
"""
date_obj = datetime.datetime.now(utc) - datetime.timedelta(7)
return date_obj
def by_active(self):
"""
Get active record
:return:QuerySet filter
"""
return self.filter(active_flg = True)
def by_newcomer(self, newcomer_flg=True):
"""
Record extraction by new player judgment
:param limit_flg: True(New player) / False(非New player)
:return:QuerySet filter
"""
return self.filter(created_at__gt=self.active_limit_time)
def by_active_newcomer(self):
"""
New active user
"""
return self.by_active().by_newcomer()
class PlayerQuerySet(QuerySet, PlayerScopesMixin):
"""
PlayerQuerySet
"""
pass
class PlayerManager(models.Manager, PlayerScopeMixin):
"""
PlayerManager
"""
def get_query_set(self):
return PlayerQuerySet(self.model, using=self._db)
class Player(models.Model):
class Meta:
app_label = 'player'
active_flg = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
> Player.by_active_newcommer() == Player.by_active().by_newcomer()
Recommended Posts