简体   繁体   中英

Import model in Django's settings.py

I'm trying to define a constant with the value of model's class in the settings.py to provide a dynamically-defined FK for one of my models:

from catalog.models import Product
PRODUCT_MODEL = Product

No surprise it's leading to an AppRegistryNotReady exception:

django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

since there was no call to django.setup() method.

If I add

import django
django.setup()

in front of the model's import, instead of AppRegistryNotReady exception, I'm getting

AttributeError: 'Settings' object has no attribute 'PRODUCT_MODEL'

when I'm using

from django.conf import settings
...

product = models.ForeignKey(
    settings.PRODUCT_MODEL, 
    related_name='order_items')

Is there any way to implement this without errors?

I'm using Python 3.5 and Django 1.9.5.

You shouldn't import models or call django.setup() in your settings file.

Instead, use a string to refer to your model.

PRODUCT_MODEL = 'catalog.Product'

Then, in your models, you can use the setting.

product = models.ForeignKey(
    settings.PRODUCT_MODEL, 
    related_name='order_items',
)

Note that the AUTH_USER_MODEL setting uses a string like this, you do not import the user model in the settings file.

Store the model name as a string.

In settings.py:

PRODUCT_MODEL = 'YourModel'

In your models.py:

from django.apps import AppConfig
....
field = models.ForeignKey(AppConfig.get_model(PRODUCT_MODEL))

(This works from Django 1.9.)

在设置和延迟导入中使用catalog.Product

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM