[英]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: 我正在尝试使用
settings.py
的model类的值定义一个常量,为我的一个模型提供动态定义的FK:
from catalog.models import Product
PRODUCT_MODEL = Product
No surprise it's leading to an AppRegistryNotReady
exception: 毫不奇怪,它导致
AppRegistryNotReady
异常:
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
since there was no call to django.setup()
method. 因为没有调用
django.setup()
方法。
If I add 如果我加
import django
django.setup()
in front of the model's import, instead of AppRegistryNotReady
exception, I'm getting 在模型的导入前面,而不是
AppRegistryNotReady
异常,我得到了
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. 我正在使用Python 3.5和Django 1.9.5。
You shouldn't import models or call django.setup()
in your settings file. 您不应导入模型或在设置文件中调用
django.setup()
。
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. 请注意,
AUTH_USER_MODEL
设置使用这样的字符串,您不会在设置文件中导入用户模型。
Store the model name as a string. 将模型名称存储为字符串。
In settings.py: 在settings.py中:
PRODUCT_MODEL = 'YourModel'
In your models.py: 在你的models.py中:
from django.apps import AppConfig
....
field = models.ForeignKey(AppConfig.get_model(PRODUCT_MODEL))
(This works from Django 1.9.) (这适用于Django 1.9。)
在设置和延迟导入中使用catalog.Product
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.