Django,从具有多对多关系的子级访问二级父级的顶级父级对象

发布于 2025-01-10 11:34:59 字数 801 浏览 0 评论 0原文

我有一个设置,里面有这些模型。

设备 幻灯片 幻灯片

该设备只能播放一张幻灯片 幻灯片可以分配给许多设备 幻灯片可以分配给许多幻灯片

现在,我正在尝试沿着树向上获取具有幻灯片所属的所有幻灯片的所有设备。

假设我拥有“幻灯片 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?

enter image description here

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

回心转意 2025-01-17 11:34:59

嗯,我想这比我想象的要容易!

devices = Device.objects.filter(slideshow__slides=instance)

Well, I guess it was easier than I thought!

devices = Device.objects.filter(slideshow__slides=instance)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文