我有一个带有 ManyToManyField 的模型和一个直通模型,其中有一个我想过滤的 bool 字段。
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
有效,还是我做错了什么?
最佳答案
来自 Using managers for related object access 上的文档:
you can force Django to use the same class as the default manager for your model by setting the use_for_related_fields attribute on the manager class.
意思是,在您的情况下,您可以强制
d.simulation
使用普通的 SimulationManager (而不是 DispatcherManager - DispatcherManager 将用于链接的相反方向。例如, Simulation.objects.get(id=1).dispatcher_set.completed
)。我认为实现你想要的最简单的方法是定义一个
get_completed_simulations
和一个 get_queued_simulations
DispatcherManager 中的方法。所以用法是 d.get_completed_simulations()
.
关于带有 ManyToManyField 的 Django 自定义管理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2031811/