Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 741
Egor Biriukov Avatar asked Jan 07 '23 04:01

Egor Biriukov


2 Answers

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.

like image 82
Alasdair Avatar answered Jan 14 '23 23:01

Alasdair


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.)

like image 38
mimo Avatar answered Jan 15 '23 01:01

mimo