2015-09-25 65 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

相關問題