django之register_model(self, app_label, model):
Posted on 2018-03-10 13:53 王将军之武库 阅读(974) 评论(0) 编辑 收藏 举报前面在阅读apps_install源码时,一直不明白app的model是什么时候导入的,今天在看modelbase源码时,看到了new_class._prepare()
new_class._meta.apps.register_model(new_class._meta.app_label, new_class)也就是说,在生成model类时会注册到自己所属的app中,在导入models.py时,就会生成model类。
def register_model(self, app_label, model): # Since this method is called when models are imported, it cannot # perform imports because of the risk of import loops. It mustn't # call get_app_config(). model_name = model._meta.model_name app_models = self.all_models[app_label]#默认词典 if model_name in app_models: if (model.__name__ == app_models[model_name].__name__ and model.__module__ == app_models[model_name].__module__): warnings.warn( "Model '%s.%s' was already registered. " "Reloading models is not advised as it can lead to inconsistencies, " "most notably with related models." % (app_label, model_name), RuntimeWarning, stacklevel=2) else: raise RuntimeError( "Conflicting '%s' models in application '%s': %s and %s." % (model_name, app_label, app_models[model_name], model)) app_models[model_name] = model#往self.all_models[app_label]加入了modle self.do_pending_operations(model) self.clear_cache()
def check_models_ready(self): """ Raises an exception if all models haven't been imported yet. """ if not self.models_ready: raise AppRegistryNotReady("Models aren't loaded yet.")
def check_models_ready(self): """ Raises an exception if models haven't been imported yet. """ if self.models is None:#如果该app没有models,就出错。 raise AppRegistryNotReady( "Models for app '%s' haven't been imported yet." % self.label)