我想警告或阻止用户删除其他实例引用的对象实例。有没有一个很好的方法来做到这一点?Django:我如何才能找到哪个模型引用模型
一种方法是获取包含指示对象的模型列表,然后尝试对它们进行反向查找。有没有办法获得这个模型列表?或者,还有更好的方法?
当调查收集的建议,我发现了一些相关的信息,并写了发现其中有所指的外键的类如下:
def find_related(cl, app):
"""Find all classes which are related to the class cl (in app) by
having it as a foreign key."""
from django.db import models
all_models = models.get_models()
ci_model = models.get_model(app, cl)
for a_model in all_models:
for f in a_model._meta.fields:
if isinstance(f, ForeignKey) and (f.rel.to == ci_model):
print a_model.__name__
基础上建议使用的代码中收集:
def find_related(instance):
"""Find all objects which are related to instance."""
for related in instance._meta.get_all_related_objects():
acc_name = related.get_accessor_name()
referers = getattr(instance, acc_name).all()
if referers:
print related
感谢您使用最终解决方案更新此问题。优秀作品。 – Spike
你有'find_related'采取'(cl,app)',而'get_model'采取'(app,cl)'。这真是令人困惑!另外,如果其他人正在阅读,'cl'和'app'是字符串 - 不要传递对象! – Casebash