带有 ManyToManyField 的 Django 自定义管理器

标签 django django-models

我有一个带有 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/

相关文章:

mysql - Django 1.7.1 中的 django.db.migrations.graph.CircularDependencyError

Django Loop 中的 Javascript 函数仅运行一次

python - 允许将 %d.%m.%Y 格式字符串传递给模型的 DateField 的最佳方法?

django - 使相当复杂的 Django 模型方法可在管理员中排序?

django - 为什么与 self 的多对多关系不能对称

Python/Django 查询 - 将原始 SQL 附加到模型对象

python - django 模型选择选项作为多选框

python - 使用月份过滤器时 Django 错误

python - 使用自定义字段扩展用户模型表单

Django 1.7 ImageField 表单验证