S
S
sortfact3332021-03-03 12:28:09
Django
sortfact333, 2021-03-03 12:28:09

How to create a parent-child relationship in a model?

I have a Category model

class Categorie(models.Model):
  name = models.CharField('categorie_name', max_length=50)
  parent = models.OneToOneField(Categorie, on_delete=models.CASCADE, blank=True)
  child = models.ManyToManyField(Categorie, blank=True)

And I want to create relation between categories
How can I do this in django?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Belokurov, 2021-03-03
@kyern

parent = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL, related_name='child')

Access to child will be possible throughObject.child.all()

G
gromyko21, 2021-03-03
@gromyko21

In general, there is a good library link to its dock django mptt just creates these relationships + a bunch of built-in methods

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question