Django:我如何找到我的模型中的哪个模型 [英] Django: How can I find which of my models refer to a model

查看:121
本文介绍了Django:我如何找到我的模型中的哪个模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提醒或阻止用户删除其他实例引用的对象实例。有没有一个很好的方式来做这个?

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


推荐答案

Django有一个叫收藏者类。 Django在执行模型删除时使用它。它的作用似乎是你想要的。通过调用 collect(),它会在模型​​图中找到对对象的所有引用。此外,它还提供了一种删除所有找到的对象的方法,一个 delete()调用。

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.

说我从来没有使用过这个类,我只知道它存在。 API有点复杂,但如果您愿意一点点挖掘Django的内部结构,那么可能会为您节省大量的编码。

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.

这篇关于Django:我如何找到我的模型中的哪个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆