Search code examples
django-modelsdjango-apps

Create a model in app1 when app2 loads


Imagine I have an app1 called 'pricelists' and app2 called 'marketplaces'.

In the marketplaces app, I want to auto create a pricelists.PriceList if it is not yet present. This PriceList is to be used in signals to auto-populate the pricelist depending on a few factors.

Currently, I use something like this in my signals:

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

I don't like this approach since it's repeated a number of times and plainly want the pricelist to be created for sure.

My question. How can I get_or_create a model-object in another app every time django restarts?

Solution

In your app.__init__.py manually define your AppConfig. It doesn't seem to get detected in django 1.10

default_app_config = 'marketplaces.apps.MarketPlacesConfig'

Override your appconfig ready method:

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']

Solution

  • AppConfig.ready() with django.db.models.signals is the only way I can think of.