什麼是使用get_model()的最佳實踐以及何時應該導入?get_model()vs from .models import somemodelname
編號:https://docs.djangoproject.com/en/1.8/ref/applications/
什麼是使用get_model()的最佳實踐以及何時應該導入?get_model()vs from .models import somemodelname
編號:https://docs.djangoproject.com/en/1.8/ref/applications/
我願意的話,使用.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,也可以幫助。
這並不回答他的問題,不是關於「簡單的方式」,而是關於良好實踐以及何時使用它。 – levi
我們有兩個問題: 什麼是使用get_model()的最佳實踐?何時應該導入? 真的很重要,它不是一個好的做法,只有在使用時。 ,如果你認爲我的回答沒有幫助,那麼它有權利給予低估。 我很抱歉讓你浪費時間閱讀它 –
當您需要動態獲取模型類時,通常使用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
)只是在代碼中的任何位置導入模型的默認方式。
這些只是例子,還有很多其他可能的情況。
[您不能在定義應用程序配置類的模塊中導入模型,但可以使用get_model()按名稱訪問模型類,如下所示:](https: //docs.djangoproject.com/en/1.8/ref/applications/#django.apps.AppConfig.ready) 因此,在這種情況下不能導入模型? – n00b
當您需要動態獲取模型類時,通常使用'get_model()'。例如,你有一個已經動態構建序列化器的應用程序,並且你將'Meta.model'設置爲剛剛用'get_model()'得到的類。另一個選項是導入模型的默認方式。 – Ivan