首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Django ManyToMany字段没有预选自定义管理器的行

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

Stack Overflow用户
提问于 2011-06-23 22:08:35
回答 1查看 695关注 0票数 0

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

我的模特是:

  • 与->相关的问题SubjectiveStatistic
  • SubjectiveStatistic将统计数据扩展为代理。它有一个自定义管理器,将结果集限制在“type”字段与“SubjectiveStatistic”匹配的地方(类型字段包含对象的类名)。

以下是一个问题:

代码语言:javascript
运行
复制
class Question(models.Model):
    subjective_statistic = models.ManyToManyField(SubjectiveStatistic, null=True, blank=True)

下面是SubjectiveStatistic:

代码语言:javascript
运行
复制
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

下面是经理:

代码语言:javascript
运行
复制
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 (但我做不到,因为这是一个内部类)或者类似的东西?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-06-23 22:49:02

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

代码语言:javascript
运行
复制
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模型的管理器,无论是直接访问还是反向访问,就像许多关系一样。

这里有更多的信息:控制自动管理器类型

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6461180

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档