如何使用django的orm找到與特定模型有關系的所有模型?

[英]How does one find all models with relations to a specific model with django's orm?


I need to combine two instances of a model, and the process I need to go through is fairly simple. There's no much if any normalized data in the system. To combine the two I would just need to merge the data, and set the relevant foreign_keys on any models related.

我需要組合一個模型的兩個實例,我需要經歷的過程非常簡單。系統中沒有任何標准化數據。要合並這兩個,我只需要合並數據,並在相關的任何模型上設置相關的foreign_keys。

The issue comes in trying to keep the app as 'reusable' as possible. I don't want to edit this module any time I add another model which might work with this one. is there a way to get a list of models with a foreign key to another specific model? and what the relevant fields are?

問題在於盡量讓應用程序保持“可重用”狀態。我不想在我添加另一個可能適用於此模型的模型時編輯此模塊。有沒有辦法獲得帶有外鍵的模型列表到另一個特定模型?以及相關領域是什么?

Also, a number of links back to this root model would be through generic foreign keys. Hoever I'm assuming finding the models linking to the root object would work on finding models linking to the ContentTypes model.

此外,返回此根模型的許多鏈接將通過通用外鍵。不過,我假設找到鏈接到根對象的模型將用於查找鏈接到ContentTypes模型的模型。

1 个解决方案

#1


1  

You might be able to pull this off via introspection, but you are tightly coupling your models to the Django implementation, which could be dangerous. If you are good with that, you could do something along the lines of:

您可以通過內省來解決這個問題,但是您正在將模型與Django實現緊密耦合,這可能很危險。如果你對此很好,你可以做一些事情:

class MyModel(models.Model):
    ## Definitions
    @property
    def related(self):
        related = []
        for attr in dir(self):
            try:
                ## Get the class name.
                attr_type = type(bf.__getattribute__(attr)).__name__
                ## This is an internal type tucked away in:
                ##     django/db/models/fields/related.py
                ##   As best I can tell, this is only used for reverse
                ##   relationships.
                if attr_type == "RelatedManager":
                    related.extend(bf.__getattribute__(attr).all())
            except:
                ## Some of the built in methods / properties throw errors,
                ##   skip them.
                pass
        return related

Might not be the best solution, but it seems to work in testing.

可能不是最好的解決方案,但它似乎在測試中起作用。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2011/07/25/724e4bc4746881bbed7df2927f097df1.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com