What is the difference between “my_app” and “my_app.apps.My_appConfig in the installed INSTALLED_APPS in settings.py?

huangapple go评论57阅读模式
英文:

What is the difference between “my_app” and “my_app.apps.My_appConfig in the installed INSTALLED_APPS in settings.py?

问题

"my_app" 和 "my_app.apps.My_appConfig" 在 settings.py 中的 INSTALLED_APPS 中有什么区别?

英文:

Im new in Django and I would like to know what is the difference between "my_app" and "my_app.apps.My_appConfig" in the installed INSTALLED_APPS in settings.py?

答案1

得分: 1

如果Django加载一个应用程序,它是通过AppConfig来加载的。AppConfig提供了如何运行应用程序的“上下文”。例如,应用程序的名称和标签,如果没有指定主键,则模型的默认主键类型。加载应用程序时要执行的任务等等,这些可以在AppConfig中定义。

您可以通过点路径加载应用程序,该路径指向AppConfig,例如<code>'<i>app_name</i>.apps.<i>MyAppConfig</i>'</code>,然后它将通过该配置加载应用程序。如果只指定应用程序的名称,例如<code>'<i>app_name</i>'</code>,那么它将查找正确的AppConfig

如果没有apps.py,或者apps.py不包含AppConfig的子类,它将仅使用AppConfig本身,该配置具有实例化应用程序的逻辑,没有任何“额外内容”。如果至少有一个AppConfig,它将查找具有default = TrueAppConfig子类,默认情况下default = True,因此如果只有一个AppConfig,并且未设置default = False,它将选择该配置。

如果有多个AppConfig具有default = True,它将引发错误,因为不清楚将使用哪个应用程序配置。因此,如果*MyAppConfig*是apps.py中唯一的AppConfig子类,并且未将default设置为False,那么<code>'<i>app_name</i>.apps.<i>MyAppConfig</i>'</code>和简单的<code>'<i>app_name</i>'</code>是等价的。

英文:

If Django loads an app, it loads so through an AppConfig. The AppConfig provides a "context" how to run the app. For example the name and label of the app, the default type for the primary key of a model if no primary key is specified. Things to do when the app is loaded and so on. These can be defined in the AppConfig.

You can load an app through a dotted path that leads to the AppConfig, so <code>'<i>app_name</i>.apps.<i>MyAppConfig</i>'</code>, then it will load the app through that config. If you only specify the name of the app, so <code>'<i>app_name</i>'</code>, then it will look for the right AppConfig.

If there is no apps.py, or that apps.py contains no subclass of AppConfig, it will just use AppConfig itself, which has logic to instantiate the app without any "extras". If there is at least one AppConfig, it will look for a subclass of AppConfig with default = True, by default default = True, so if there is a single AppConfig, and one did not set default = False, it will pick that one.

If there are multiple AppConfigs with default = True, it will raise an error, since then it is unclear what app config will be used. If MyAppConfig is thus the only subclass of AppConfig in apps.py and default is not set to False for that one <code>'<i>app_name</i>.apps.<i>MyAppConfig</i>'</code> and simply <code>'<i>app_name</i>'</code> are thus equivalent.

huangapple
  • 本文由 发表于 2023年5月15日 05:29:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76249764.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定