加载 app2 时在 app1 中创建模型

Create a model in app1 when app2 loads

假设我有一个名为 'pricelists' 的应用程序 1 和一个名为 'marketplaces' 的应用程序 2。

在市场应用程序中,我想自动创建一个 pricelists.PriceList(如果它还不存在)。此价目表将用于根据几个因素自动填充价目表的信号。

目前,我在我的信号中使用这样的东西:

price_list, _ = PriceList.objects.get_or_create(
    currency='EUR', is_default=False, customer_type='CONS',
    remarks='Marketplace')

我不喜欢这种方法,因为它重复了很多次,而且显然希望确定地创建价目表。

我的问题。每次 django 重新启动时,如何 get_or_create 另一个应用程序中的模型对象?

解决方案

在您的 app.__init__.py 中手动定义您的 AppConfig。它似乎没有在 django 1.10

中被检测到
default_app_config = 'marketplaces.apps.MarketPlacesConfig'

覆盖您的 appconfig 就绪方法:

class MarketPlacesConfig(AppConfig):
    name = 'marketplaces'

    def ready(self):
        from pricelists.models import PriceList, PriceListItem
        price_list_marketplaces, _ =  PriceList.objects.get_or_create(
            **settings.MARKETPLACES['price_list']

AppConfig.ready()django.db.models.signals 是我能想到的唯一方法。