2010-01-09 187 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()