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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With