I’m just getting my hands on Django Managers and I’ve found myself doing this type of programming. I’m looking to see if there is a way to remove the obvious repetition.. I believe I need to define use get_query_set to refer to myself?
To be very clear on my question. I am repeatadly having to pass in the subdivision in order to figure out the rows from which to filter on. I think there is an easier way I’m just not sure what it is.
Thanks for looking!!
— models.py
class Subdivision(models.Model):
objects = SubdivisionManager()
— managers.py
class SubdivisionManager(models.Manager):
"""A generic manager with metros"""
def is_metro_sample_eligible(self, subdivision_id):
"""Are we eligible for sampling taking into account the 90 day windows"""
from .models import Subdivision
subdivision = Subdivision.objects.get(id=subdivision_id)
return True
def get_available_subdivisions(self, subdivision_id):
"""Return all potential subdivisions for a builder in a metro"""
from .models import Subdivision
subdivision = Subdivision.objects.get(id=subdivision_id)
return self.filter(builder_org=subdivision.builder_org,
metro=subdivision.metro)
def get_available_sampling_subdivisions(self, subdivision_id):
"""Return Subdivision which are able to participate in metro sampling"""
from .models import Subdivision
subdivision = Subdivision.objects.get(id=subdivision_id)
return self.filter(builder_org=subdivision.builder_org,
metro=subdivision.metro,
use_sampling = True,
use_metro_sampling = True)
Actually, I’d put
is_metro_sample_eligible()onSubdivision, since each call needs to access an instance.And then I’d either move
get_available_subdivisions()andget_available_sampling_subdivisions()onto yourbuilder_orgmodelor leave it on the manager, and revise the signature to
get_available_subdivisions(self, builder_org, metro).Rationale- I could imagine needing to call
get_available_subdivisions()without actually having aSubdivisionalready in mind- clearly the important pieces of information are the builder organization and the metro.