django.db.models.loading.get_model与导入 [英] django.db.models.loading.get_model vs. importing
问题描述
从django.db.models.loading导入get_model
$有什么不利之处? b $ b def get_something():
model = get_model('app','Model')
return model.something()
而不是
来自app.models import模型
def get_something():
return Model.something()
第二个例子可以导致循环依赖,而第一个例子不是,但第二个例子更经常看到。
更新:你会得到循环依赖性错误,如果第二个例子在一个名为Other_Model的模型中,并且Model导入了Other_Model以及一个简单的循环导入。
通常, get_model
功能被保留用于需要动态加载模型的时间(例如,如果您不知道是否有人会通过一个服务myapp.Person,一个myapp.Place或一个myapp.Thing,他们都有相同的界面)。如果没有其他原因导致意想不到的事实,我将会说,任何其他用途应该在代码审查中自动标记。
As对于内部力学,真的没有什么大的差别。不可避免地, get_model
版本将调用 __ import __
。也就是说,它不是没有bug 。使用实际的导入
语句将避免此问题。
As对于MRO问题,通过重构无法解决循环进口是一种罕见的情况。如果你有两个应用程序是如此相互依赖的,它们导致循环导入,那么你真的需要重新考虑这些应用程序。 (我的猜测是,你真的在处理一个应用程序。)
Is there any downside to using something like
from django.db.models.loading import get_model
def get_something():
model = get_model('app', 'Model')
return model.something()
instead of
from app.models import Model
def get_something():
return Model.something()
The second example can lead to circular dependencies while the first example does not, but the second example is seen much more often.
Update: You would get circular dependency errors if the second example was in a model called Other_Model and Model imported Other_Model as well -- a simple circular import.
Generally, the get_model
functionality is reserved for times when a model needs to be loaded dynamically (say, if you don't know if someone will pass a service a myapp.Person, a myapp.Place, or a myapp.Thing and they all have the same interface). I will go so far as to say that any other use should be auto-flagged in code review if for no other reason than the fact that it introduces the unexpected.
As to internal mechanics, there really isn't a substantial difference. Inevitably the get_model
version will call __import__
. That said, it is not without bugs. Use of actual import
statements will avoid this problem.
As to MRO issues, it is a rare situation where circular imports could not be resolved by refactoring. If you have two apps which are so interdependent that they cause a circular import, then you really need to re-think those apps. (My guess is that you are really dealing with one app.)
这篇关于django.db.models.loading.get_model与导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!