Hello all! I have a question about how to write my Django Models for my needs. I believe I dont have a full understanding of Django ORM to know what I need to do. At a high level I have a model that has two props
parent which will reference the same model. A second prop would be
children which would (I think) a
ManyToManyField again on itself. This all works great, but with the
ManyToManyField the one entity will have reference to both Tags though the look up table. What i am trying to do is have the
parent prop be mapped to the parent Tag and then the
parent model will have it in the
class Tag(base): name: models.TextString() parent: models.ForeignKey('self', on_delete=models.CASCADE) children: models.ManyToMany("self")
So when I create a
Tag I can also create its children and then associate that child to its parent. But the catch is the children can have children and when I go to query the children I dont want to see the reference to the parent.
tag = Tag.objects.get(pk=1) tag.children == [Tag2, Tag3, Tag4] tag_child_1 = tag.children tag_child_1.parent == tag tag_child_1.children == [Tag5, Tag6]
Sorry if my pseudo code doesnt make sense.
Any help would be helpful!!
I finally solved this with a model structure like so:
class Tag(models.Model): name = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return self.name class Node(models.Model): tag = models.ForeignKey(Tag, on_delete=models.CASCADE) parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE, related_name="node_parent") node_list = models.ManyToManyField('self', null=True, blank=True) def __str__(self): return self.tag.name
This does what i needed! Thank you all how viewed the post!