问题描述
我很难理解为什么Django / python不允许循环导入。不用使用 apps.get_model
然后硬编码模型的标签和名称,还有什么办法解决?
I have a problem understanding why Django/python doesn't allow circular imports. Is there any way around it without using apps.get_model
and then hardcoding the label and name of the model?
假设我有2个模型 A
和 B
,其中 A
有 B
和 B
的FK具有基于 A
。
Supposing I have 2 models A
and B
where A
has a FK to B
and B
has some properties based on A
.
模型 A
model A
from main import B
field = models.ForeignKey(B, default=None)
模型 B
model B
# from main import A // this does not work
@property
def last_used(self):
A = apps.get_model(app_label='main', model_name= 'A')
唯一的解决方法是上面的代码,如果我尝试导入 A
并使用 A.objects.filter
我得到 ImportError:无法导入名称
错误。
The only way to go around it is the code above, if i try to import A
and use A.objects.filter
I get ImportError: cannot import name
error.
我的问题是当我重构代码时,它变成了查找所有那些硬编码的模型名称的麻烦。
My problem is when I refactor the code, it becomes a hassle to look for all those hardcoded model names.
这是一个不好的设计,我应该完全更改模型背后的逻辑吗?
Is this a bad design and I should completely change the logic behind my models?
推荐答案
您根本不需要在B内部导入A。由于A具有指向B的外键,因此可以使用反向关系:
You shouldn't need to import A at all inside B. Since A has a ForeignKey to B, you can use the reverse relation:
@property
def last_used(self):
return self.a_set.last()
这篇关于循环进口动机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!