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

时间:2021-11-01 21:23:11

I'd like to warn or prevent a user from deleting an object instance which is referred to by other instances. Is there a nice way to do this?

我想警告或阻止用户删除其他实例引用的对象实例。有一个很好的方法来做到这一点?

One way would be to get a list of models which include the referent and then try reverse look-ups on them. Is there a way to get that list of models? Or is there a better way?

一种方法是获得包含指示物的模型列表,然后尝试对它们进行反向查找。有没有办法获得模型列表?或者,还有更好的方法?

While investigating the collector suggestion, I found some related information and wrote the following which finds the classes which have the referent as a foreign key:

在调查收集器的建议时,我发现了一些相关的信息,并编写了以下内容,找到了具有指示对象的类:

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__

Based on suggestion to use the code in 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

1 个解决方案

#1


3  

Django has something called Collector class. It is used by Django when performing a model deletion. What it does seems like exactly what you want. By calling collect() it finds all the references to the object in the model graph. Additionally it offers a way to delete all the found objects, with a delete() call.

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

That said I've never used this class myself, I just know it exists. The API is somewhat convoluted, but if you're willing to dig into the internals of Django a little bit, it might save you a lot of coding.

那说我自己从未使用过这门课,我只知道它存在。 API有点令人费解,但是如果你愿意稍微深入研究一下Django的内部,它可能会为你节省很多代码。

#1


3  

Django has something called Collector class. It is used by Django when performing a model deletion. What it does seems like exactly what you want. By calling collect() it finds all the references to the object in the model graph. Additionally it offers a way to delete all the found objects, with a delete() call.

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

That said I've never used this class myself, I just know it exists. The API is somewhat convoluted, but if you're willing to dig into the internals of Django a little bit, it might save you a lot of coding.

那说我自己从未使用过这门课,我只知道它存在。 API有点令人费解,但是如果你愿意稍微深入研究一下Django的内部,它可能会为你节省很多代码。