我需要组合模型的两个实例,我需要经历的过程非常简单。系统中没有任何标准化数据。要合并两者,我只需要合并数据,并在相关的任何模型上设置相关的foreign_keys。
问题在于尽量让应用程序保持“可重用”状态。我不想在我添加另一个可能适用于此模型的模型时编辑此模块。有没有办法获得带有外键的模型列表到另一个特定模型?以及相关领域是什么?
此外,返回此根模型的许多链接将通过通用外键。不过,我假设找到链接到根对象的模型可以找到链接到ContentTypes模型的模型。
答案 0 :(得分:1)
您可以通过内省来解决此问题,但是您将模型与Django实现紧密耦合,这可能很危险。如果你对此很好,你可以做一些事情:
class MyModel(models.Model):
## Definitions
@property
def related(self):
related = []
for attr in dir(self):
try:
## Get the class name.
attr_type = type(bf.__getattribute__(attr)).__name__
## This is an internal type tucked away in:
## django/db/models/fields/related.py
## As best I can tell, this is only used for reverse
## relationships.
if attr_type == "RelatedManager":
related.extend(bf.__getattribute__(attr).all())
except:
## Some of the built in methods / properties throw errors,
## skip them.
pass
return related
可能不是最佳解决方案,但它似乎可以用于测试。