获取所有相关的Django模型对象 [英] Get all related Django model objects

查看:169
本文介绍了获取所有相关的Django模型对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取所有具有指向对象的ForeignKey的模型对象的列表? (类似于DELETE CASCADE之前的Django管理员中的删除确认页面)。



我试图提出一种在数据库中合并重复对象的通用方法。基本上,我想要所有具有ForeignKeys的对象指向B来更新以指向对象A,所以我可以删除B,而不会丢失任何重要的东西。


$ b $感谢您的帮助!

解决方案

Django< = 1.7



这给你所有相关对象的属性名称:

  links = [rel.get_accessor_name()for rel a._meta.get_all_related_objects()] 

然后可以使用这样的东西来获取所有相关对象:

 链接中的链接:
objects = getattr(a,link).all()
对象中的对象:
#执行相关对象实例

我花了一段时间尝试这样做,所以我可以在
上实现一种观察者模式,我的一个模型。希望这是有帮助的。



Django 1.8 +



使用 _meta.get_fields() / code>: https://docs.djangoproject.com/en/1.10/ref/models/meta/#django.db.models.options.Options.get_fields (参见 _get_fields中的相反() source))


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).

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.

Thanks for your help!

解决方案

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.

Django 1.8+

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屋!

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