【问题标题】:Using another model manager's code in a Django custom manager class在 Django 自定义管理器类中使用另一个模型管理器的代码
【发布时间】:2012-04-20 01:02:59
【问题描述】:

我有两个模型,例如 QuestionTopic

我正在尝试向 Question 模型的自定义管理器添加方法,例如一些按Topic过滤的方法。

我似乎不能为此使用其他经理的代码(也不能import Topic,所以我不能这样做Topic.objects...

class QuestionManager

def my_feed(self, user):
       topics = TopicManager().filter(user=user) # 1st approach
       #topics = Topic.objects.filter(user=user) # 2nd line
       # do something with topics

类主题管理器 ....

使用第一种方法,我收到以下错误:

virtualenv/local/lib/python2.7/site-packages/django/db/models/sql/query.pyc in get_meta(self)
    219         by subclasses.
    220         """
--> 221         return self.model._meta
    222 
    223     def clone(self, klass=None, memo=None, **kwargs):

AttributeError: 'NoneType' object has no attribute '_meta'

我不能使用第二行,因为我不能导入主题,因为主题依赖于这个文件中的主题管理器。有解决办法吗?

【问题讨论】:

    标签: django django-orm django-managers


    【解决方案1】:

    在任何情况下,您都不能直接使用经理。您总是通过模型类访问它。

    如果由于循环依赖而无法在文件顶部导入模型,则只需在方法中导入即可。

    【讨论】:

    • 导入 inside 方法会对性能造成什么影响?任何指针将不胜感激。
    【解决方案2】:

    你应该可以把它放在managers.py 模块的底部:

    # Prevent circular import error between models.py and managers.py
    from apps.drs import models
    

    在您的管理器类中,您可以使用 models.<modelname> 引用其他模型,这应该可以工作,避免循环导入。

    例如:

    class QuestionManager(Manager):
    
        def my_feed(self, user):
            topics = models.Topic.objects.filter(user=user)
            # do something with topics
    
    # Prevent circular import error between models.py and managers.py
    from apps.drs import models
    

    这是有效的,因为您正在导入模块,而不是模型类,这会导致延迟导入。到函数运行时,模块将被导入,一切都会正常工作。

    您还可以使用 django.apps.get_model() 按名称加载模型:

    from django.apps import apps
    apps.get_model('my_app', 'MyModel')
    

    详情here

    例如:

    from django.apps import apps
    
    class QuestionManager(Manager):
    
        def my_feed(self, user):
            topics = apps.get_model('my_app', 'Topic').objects.filter(user=user)
            # do something with topics
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-20
      • 2021-07-03
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多