'Django, accessing the top parent objects from second level parents from child with many to many realtaionship
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)
Solution 1:[1]
Well, I guess it was easier than I thought!
devices = Device.objects.filter(slideshow__slides=instance)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | VIDesignz |

