A
A
Animkim2016-05-09 13:28:17
Django
Animkim, 2016-05-09 13:28:17

Django category tree how to limit nesting?

class Category(models.Model):
    parent = models.ForeignKey('self', null=True, blank=True, related_name='children')
    title = models.CharField(max_length=50)

There is such a model, it is known in advance that the maximum nesting is no more than three.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2016-05-09
@Animkim

First, use MPTT. Second, override the save() method and check the parent's level attribute in it.

class Category(mptt.models.MPTTModel):
    parent = mptt.models.TreeForeignKey('self', null=True, blank=True, related_name='children')
    title = models.CharField(max_length=50)

    def save(self, *args, **kwargs):
        if parent.level == 3:
            raise ValueError(u'Достигнута максимальная вложенность!')
        super(Category, self).save(*args, **kwargs)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question