我有一个带有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.simulations.completed()
或d.simulations.queued()
但这些似乎不像我有的那样工作预期。我误解了use_for_related_fields
是如何运作的,还是我做错了什么?
答案 0 :(得分:3)
来自Using managers for related object access上的文档:
您可以通过在manager类上设置use_for_related_fields属性,强制Django使用与模型的默认管理器相同的类。
意思是,在您的情况下,您可以强制d.simulation
使用普通的SimulationManager(而不是DispatcherManager - DispatcherManager将用于链接的相反方向。例如,Simulation.objects.get(id=1).dispatcher_set.completed
)。< / p>
我认为实现所需内容的最简单方法是在DispatcherManager中定义get_completed_simulations
和get_queued_simulations
方法。因此用法为d.get_completed_simulations()
。