Django:我怎样才能找到我的模型中的哪个模型

Mit*_*tch 11 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__
Run Code Online (Sandbox Code Playgroud)

根据建议使用收集中的代码:

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
Run Code Online (Sandbox Code Playgroud)

jul*_*icz 4

Django 有一个叫做Collector类的东西。Django 在执行模型删除时使用它。它所做的似乎正是您想要的。通过调用collect()它可以找到模型图中对该对象的所有引用。此外,它还提供了一种通过调用删除所有找到的对象的方法delete()

也就是说,我自己从未使用过这个类,我只知道它存在。该 API 有点复杂,但如果您愿意深入了解 Django 的内部原理,它可能会为您节省大量编码。