Home > Software design >  How to make relation between rows in the same table in Django
How to make relation between rows in the same table in Django

Time:05-09

Let me show an example first:

Table1:
id | sub_is | name
---|--------|-----
1   | null    | group 1
2   | 1        | group 2
3   | 1        | group 3
4   | 2        | group 4
5   | 2        | group 5
6   | 3        | group 6
7   | 1        | group 7
8   | 4        | group 8

It will be look like a small structure:

group 1
|- group 2
|     |-group 4
|     |     |-hroup 8
|     |-group 5
|- group 3
|     |-group 6
|- group 7

My question is:
How can I do this in Django?
How, if it is possible, I can make relation between two rows in the same table?

Thanks for any suggestions and any help.

CodePudding user response:

Maybe this will help you

class Foo(models.Model):
  bar = models.ManyToManyField(Child, related_name="bar")
  baz = models.ManyToManyField(Child, related_name="baz")

CodePudding user response:

I tried something like this but it doesn't work:

class Department(models.Model):
sub_id = models.ForeignKey(Department, on_delete=models.CASCADE)
name = models.CharField(max_length=60, unique=False)

def __str__(self):
    return self.name

This way I cannot call the field with the name of the class I'm in.

  • Related