Django经理或更好的计划

时间:2012-02-18 04:29:10

标签: django django-managers

我只是亲自动手Django Managers而且我发现自己正在进行这种类型的编程。我正在寻找是否有办法消除明显的重复..我相信我需要定义使用get_query_set来引用自己?

要清楚我的问题。我重复通过细分以找出要过滤的行。我认为有一种更简单的方法,我只是不确定它是什么。

感谢您的期待!!

--- 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)

1 个答案:

答案 0 :(得分:1)

实际上,我将is_metro_sample_eligible()放在Subdivision上,因为每次调用都需要访问一个实例。

class Subdivision(models.Model):
    def is_metro_sample_eligible(self):
        """Are we eligible for sampling taking into account the 90 day windows"""
        #TODO do something useful here and return true or false
        return True

然后我会将get_available_subdivisions()get_available_sampling_subdivisions()移到您的builder_org型号上

from .models import Subdivision

class BuilderOrg(models.Model):
    #whatever you have goes here
    def get_available_subdivisions(self, metro):
        """Return all potential subdivisions for a builder in a metro"""
        return Subdivision.objects.filter(builder_org=self,
                                          metro=metro)

    def get_available_sampling_subdivisions(self, metro):
        """Return Subdivision which are able to participate in metro sampling"""
        return Subdivision.objects.filter(builder_org=self,
                                          metro=metro,
                                          use_sampling = True,
                                          use_metro_sampling = True)

或将其保留在经理身上,并将签名修改为get_available_subdivisions(self, builder_org, metro)

理由 - 我可以想象在没有实际考虑get_available_subdivisions()的情况下需要致电Subdivision - 显然重要的信息是建设者组织和地铁。