2010-01-09 185 views
11

我有一个模型与ManyToManyField与直通模型,其中有一个布尔字段,我想过滤。Django与ManyToManyField的自定义管理器

from simulations.models import * 
class DispatcherManager(models.Manager): 
    use_for_related_fields = True 

    def completed(self): 
     original = super(DispatcherManager,self).get_query_set() 
     return original.filter(dispatchedsimulation__status=True) 
    def queued(self): 
     original = super(DispatcherManager,self).get_query_set() 
     return original.filter(dispatchedsimulation__status=False) 

class Dispatcher(models.Model): 
    name = models.CharField(max_length=64) 
    simulations = models.ManyToManyField('simulations.Simulation', 
      through='DispatchedSimulation') 
    objects = DispatcherManager() 

class DispatchedSimulation(models.Model): 

    dispatcher = models.ForeignKey('Dispatcher') 
    simulation = models.ForeignKey('simulations.Simulation') 
    status = models.BooleanField() 

我认为use_for_related_fields变量,让我来过滤M2M结果上像这样一个调度器d:d.simulations.completed()d.simulations.queued()但这些不会出现,因为我早就预料到工作。我误解use_for_related_fields是如何工作的,或者我做错了什么?

回答

3

从文档上Using managers for related object access

您可以强制的Django通过设置use_for_related_fields的经理类属性使用相同的类默认经理模型

含义,你的情况,你可以强制d.simulation使用正常SimulationManager(而不是DispatcherManager - DispatcherManager将用于链路的方向相反。例如,Simulation.objects.get(id=1).dispatcher_set.completed)。

我认为最简单的方法来实现你想要的是在DispatcherManager中定义get_completed_simulationsget_queued_simulations方法。所以用法是d.get_completed_simulations()