【发布时间】:2011-11-24 06:05:26
【问题描述】:
我想警告或阻止用户删除其他实例引用的对象实例。有什么好办法吗?
一种方法是获取包含所指对象的模型列表,然后尝试对其进行反向查找。有没有办法获得该模型列表?还是有更好的办法?
在调查收集器建议时,我找到了一些相关信息并编写了以下内容,以查找具有引用作为外键的类:
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__
基于使用collect代码的建议:
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
【问题讨论】:
-
感谢您使用最终解决方案更新此问题。出色的工作。
-
你有
find_related使用(cl, app),而get_model使用(app, cl)。真的很混乱!此外,如果其他人正在阅读本文,cl和app是字符串 - 不要传递对象!
标签: django