How to implement "named_scope" of RubyOnRails with Django

Overview

I tried something like named_scope in RubyOnRails with Django

code

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)

Code execution example

> Player.by_active_newcommer() == Player.by_active().by_newcomer()

Recommended Posts

How to implement "named_scope" of RubyOnRails with Django
How to get started with Django
How to authenticate with Django Part 2
How to authenticate with Django Part 3
How to do arithmetic with Django template
How to check the version of Django
Here's a brief summary of how to get started with Django
How to develop a cart app with Django
How to specify attributes with Mock of python
How to deal with garbled characters in json of Django REST Framework
How to output CSV of multi-line header with pandas
How to infer MAP estimate of HMM with PyStruct
How to infer MAP estimate of HMM with OpenGM
How to learn structured SVM of ChainCRF with PyStruct
Summary of how to share state with multiple functions
How to update with SQLAlchemy?
How to cast with Theano
How to Alter with SQLAlchemy?
How to separate strings with','
How to RDP with Fedora31
How to Delete with SQLAlchemy?
How to handle static files when deploying to production with Django
How to check ORM behavior in one file with django
How to enable Read / Write of net.Conn with context with golang
[Django] How to give input values in advance with ModelForm
How to resolve CSRF Protection when using AngularJS with Django
How to display a list of installable versions with pyenv
I tried to implement ListNet of rank learning with Chainer
Steps to develop Django with VSCode
Python: How to use async with
[Django] How to test Form [TDD]
Summary of how to use pandas.DataFrame.loc
How to use virtualenv with PowerShell
How to deal with imbalanced data
How to install python-pip with ubuntu20.04LTS
Common html to rent with Django
How to deal with imbalanced data
Summary of how to use pyenv-virtualenv
How to get started with Scrapy
How to get started with Python
How to reflect CSS in Django
How to deal with DistributionNotFound errors
How to Data Augmentation with PyTorch
How to use FTP with Python
How to calculate date with python
How to write Django1.9 environment-independent wsgi.py
How to install mysql-connector with pip3
Summary of how to use csvkit
How to INNER JOIN with SQLAlchemy
How to install Anaconda with pyenv
How to extract features of time series data with PySpark Basics
How to deal with "You have multiple authentication backends configured ..." (Django)
[Hugo] Summary of how to add pages to sites built with Learn
How to implement Java code in the background of RedHat (LinuxONE)
How to monitor the execution status of sqlldr with the pv command
Explain how to use TensorFlow 2.X with implementation of VGG16 / ResNet50
Node.js: How to kill offspring of a process started with child_process.fork ()
[Tips] How to do template extends when creating HTML with django
Step notes to get started with django
[Python] Summary of how to use pandas
How to title multiple figures with matplotlib