Hi,
I am now trying, for days, to get a tree like view from my assembly model into my template. I think I have read everything what I have found on StackOverflow and other sites. Somehow I am not able to get it working. I am trying to not use any 3rd party extensions => I'm happy to be proven wrong. But first let me explain my topic:
This are my models:
class Assembly(models.Model):
reference = models.OneToOneField('products.Reference', on_delete=models.RESTRICT, verbose_name=_('reference'))
subassembly = models.ManyToManyField(SubAssembly, blank=True, verbose_name=_('subassembly'))
component = models.ManyToManyField(Component, blank=True, verbose_name=_('component'))
class SubAssembly(models.Model):
reference = models.CharField(max_length=40, default=None)
subassembly_class = models.ForeignKey(SubAssemblyClass, on_delete=models.CASCADE)
nested_subassembly = models.ManyToManyField(
'self', symmetrical=False, blank=True)
class SubAssemblyClass(models.Model):
name = models.CharField(max_length=255)
class Component(models.Model):
reference = models.CharField(max_length=40, unique=True)
component_class = models.ForeignKey(ComponentClass, on_delete=models.CASCADE)
nested_component = models.ManyToManyField('self', blank=True')
class ComponentClass(models.Model):
name = models.CharField(max_length=255, unique=True)
For my view I am using the class based one. I am generally using CBV's
class AssemblyDetailView(LoginRequiredMixin, DetailView):
model = Assembly
template_name = "engineering/assembly/assembly_detail.html"
Now I want in my template all children of subassembly and component from one assembly like this:
assembly1
* subassembly1
* subassembly5
* component5
* component7
* component8
* subassembly6
* component7
* component8
* component1
* component2
* subassembly2
* component3
* subassembly3
* subassembly6
* component1
* component2
* component1
* component3
The depth can be infinity but for now there will be only 3-5 levels. I don’t care if it will be Depth-first-search or Breadth-first-search. I read a lot about recursive common table expressions and raw queries. I haven’t found a way to code the logic with my complicated ManyToMany fields.
I hope there is someone out there who can help me out. Maybe I have build up the models in a wrong way and that’s causing the problems why I am not able to solve it or or something else.
Thank you for your help!