Django ManyToMany字段没有预先选择自定义管理器的行

时间:2011-06-23 22:08:36

标签: django django-models

Django 1.2.5:我有一个带有自定义管理器的模型。数据保存正确,但无法正确检索相关对象。

我的模特是:

  • 问题 - >与SubjectiveStatistic相关的
  • SubjectiveStatistic将Statistic扩展为代理。它有一个自定义管理器,只将结果集限制在'type'字段匹配'SubjectiveStatistic'的位置(类型字段包含对象的类名)。

以下是问题:

class Question(models.Model):
    subjective_statistic = models.ManyToManyField(SubjectiveStatistic, null=True, blank=True)

这是SubjectiveStatistic:

class SubjectiveStatistic(Statistic):
    ## Use a custom model manager so that the default object collection is
    # filtered by the object class name.
    objects = RestrictByTypeManager('SubjectiveStatistic')

    ## Override the __init__ method to set the type field
    def __init__(self, *args, **kwargs):
        self.type = self.__class__.__name__
        return super(SubjectiveStatistic, self).__init__(*args, **kwargs)

    class Meta:
        proxy = True

以下是经理:

from django.db import models

## Custom model manager that returns objects filtered so that 'type' == a
# given string.
class RestrictByTypeManager(models.Manager):
    def __init__(self, type='', *args, **kwargs):
        self.type = type
        return super(RestrictByTypeManager, self).__init__(*args, **kwargs)

    def get_query_set(self):
        return super(RestrictByTypeManager, self).get_query_set().filter(type=self.type)

我需要做什么才能正确返回相关对象?尽管数据库中存在关系,但是question.subjective_statistic.exists()不会返回任何内容。

也许是因为RestrictByTypeManager扩展了Manager而不是ManyRelatedManager(但我不能,因为那是一个内部类)或类似的东西?

1 个答案:

答案 0 :(得分:0)

要使用Question模型中的自定义管理器,请在自定义管理器的定义中添加use_for_related_fields = True

from django.db import models

## Custom model manager that returns objects filtered so that 'type' == a
# given string.
class RestrictByTypeManager(models.Manager):

    use_for_related_fields = True

    def __init__(self, type='', *args, **kwargs):
        self.type = type
        return super(RestrictByTypeManager, self).__init__(*args, **kwargs)

    def get_query_set(self):
        return super(RestrictByTypeManager, self).get_query_set().filter(type=self.type)

这样,RestrictByTypeManager将直接或反向访问SubjectiveStatistic模型的管理员,就像许多关系一样。

此处有更多信息:Controlling automatic Manager types

相关问题