获取所有相关的 Django 模型对象 [英] Get all related Django model objects
问题描述
如何获取具有指向对象的 ForeignKey 的所有模型对象的列表?(类似于 DELETE CASCADE 之前 Django 管理中的删除确认页面).
How can I get a list of all the model objects that have a ForeignKey pointing to an object? (Something like the delete confirmation page in the Django admin before DELETE CASCADE).
我正在尝试提出一种合并数据库中重复对象的通用方法.基本上,我希望将 ForeignKeys 指向对象B"的所有对象更新为指向对象A",这样我就可以删除B"而不会丢失任何重要的东西.
I'm trying to come up with a generic way of merging duplicate objects in the database. Basically I want all of the objects that have ForeignKeys points to object "B" to be updated to point to object "A" so I can then delete "B" without losing anything important.
感谢您的帮助!
推荐答案
Django <= 1.7
这为您提供了所有相关对象的属性名称:
Django <= 1.7
This gives you the property names for all related objects:
links = [rel.get_accessor_name() for rel in a._meta.get_all_related_objects()]
然后你可以使用这样的东西来获取所有相关的对象:
You can then use something like this to get all related objects:
for link in links:
objects = getattr(a, link).all()
for object in objects:
# do something with related object instance
我花了一段时间试图弄清楚这一点,所以我可以在上面实现一种观察者模式"我的模型之一.希望有帮助.
I spent a while trying to figure this out so I could implement a kind of "Observer Pattern" on one of my models. Hope it's helpful.
使用_meta.get_fields()
:https://docs.djangoproject.com/en/1.10/ref/models/meta/#django.db.models.options.Options.get_fields(见反向在 _get_fields()
源代码中)
Use _meta.get_fields()
: https://docs.djangoproject.com/en/1.10/ref/models/meta/#django.db.models.options.Options.get_fields (see reverse in the _get_fields()
source also)
这篇关于获取所有相关的 Django 模型对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!