Django,从具有多对多关系的子级访问二级父级的顶级父级对象
我有一个设置,里面有这些模型。
设备 幻灯片 幻灯片
该设备只能播放一张幻灯片 幻灯片可以分配给许多设备 幻灯片可以分配给许多幻灯片
现在,我正在尝试沿着树向上获取具有幻灯片所属的所有幻灯片的所有设备。
假设我拥有“幻灯片 1”对象。是否有一个查询可以让我获得树顶部的所有设备?
就是我遍历到顶部的方式,因为我需要发送 post_save 信号,它按原样工作,但我觉得这是一个不好的方法。连我都很难跟上。我正在使用相关的名称来上树。
相关_名称=设备
instance.slideshows.all
我希望做一些简单的事情,比如instance.slideshows.devices.all(),但这会产生相关的管理器错误,甚至 ().devices.all()
slideshows = instance.slideshows.all()
related_devices = []
for slideshow in slideshows:
devices = slideshow.devices.all()
related_devices = list(chain(related_devices, devices))
for device in related_devices:
post_save.send(Device, instance=device)
I have a setup where I have these models.
Devices
Slideshows
Slides
The device can have only one slideshow
Slideshow can be assigned to many devices
The slide can be assigned to many slideshows
Now, I am trying to work my way up the tree to get all of the devices that have all the slideshows that the slide belongs to.
Lets say I have a hold of the 'slide 1' object. Is there a query that could get me all the devices at the top of the tree?
Currently, this is how I am traversing to the top as I need to send a post_save signal, it is working as is but I feel like it is a bad way to do it. and it's hard for even me to follow. I am using related names to go up the tree.
related_name=devices
related_name=slideshows
I was hoping to do something simple like instance.slideshows.devices.all()
but that yields related manager errors or even instance.slideshows.all().devices.all()
slideshows = instance.slideshows.all()
related_devices = []
for slideshow in slideshows:
devices = slideshow.devices.all()
related_devices = list(chain(related_devices, devices))
for device in related_devices:
post_save.send(Device, instance=device)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
嗯,我想这比我想象的要容易!
devices = Device.objects.filter(slideshow__slides=instance)
Well, I guess it was easier than I thought!
devices = Device.objects.filter(slideshow__slides=instance)