Import model in Django's settings.py

Submitted 3 years, 6 months ago
Ticket #197
Views 294
Language/Framework Django
Priority Medium
Status Closed

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  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  using :

from django.conf import settings
...

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

 using Python 3.5 and Django 1.9.5.

Submitted on Oct 04, 20
add a comment

1 Answer

Verified

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',
)

Submitted 3 years, 6 months ago


Latest Blogs