2015-09-25 59 views

回答

-1

我愿意的话,使用.models进口,原因是一个简单的方式来获得的模型对象。
但是,如果你使用元类,也许get_model,将是最好的选择。

def get_model(self, app_label, model_name=None): 
     """ 
     Returns the model matching the given app_label and model_name. 

     As a shortcut, this function also accepts a single argument in the 
     form <app_label>.<model_name>. 

     model_name is case-insensitive. 

     Raises LookupError if no application exists with this label, or no 
     model exists with this name in the application. Raises ValueError if 
     called with a single argument that doesn't contain exactly one dot. 
     """ 
     self.check_models_ready() 
     if model_name is None: 
      app_label, model_name = app_label.split('.') 
     return self.get_app_config(app_label).get_model(model_name.lower()) 

也许这个SO POST,也可以帮助。

+0

这并不回答他的问题,不是关于“简单的方式”,而是关于良好实践以及何时使用它。 – levi

+0

我们有两个问题: 什么是使用get_model()的最佳实践?何时应该导入? 真的很重要,它不是一个好的做法,只有在使用时。 ,如果你认为我的回答没有帮助,那么它有权利给予低估。 我很抱歉让你浪费时间阅读它 –

1

当您需要动态获取模型类时,通常使用get_model()

一个实际的例子:在为迁移编写RunPython操作时,您将应用程序注册表作为其中一个参数,并使用apps.get_model('TheModel')导入历史模型。

另一个例子:你有一个应用程序已经动态构建了序列化器,并且你将它们的Meta.model设置为你刚用get_model()得到的类。

又一例子是用self.get_model()导入AppConfig.ready()中的模型。

重要的是要记住,如果您使用的是AppConfig.get_model()apps.get_models(),那么只有在应用程序注册表完全填充后才能使用它们。

其他选项(from .models import TheModel)只是在代码中的任何位置导入模型的默认方式。

这些只是例子,还有很多其他可能的情况。

+0

[您不能在定义应用程序配置类的模块中导入模型,但可以使用get_model()按名称访问模型类,如下所示:](https: //docs.djangoproject.com/en/1.8/ref/applications/#django.apps.AppConfig.ready) 因此,在这种情况下不能导入模型? – n00b

相关问题