I
I
Ilya Oskin2017-01-31 15:32:50
Django
Ilya Oskin, 2017-01-31 15:32:50

How to check for a recursive ForeignKey relationship in a model?

The model is bound to itself through FK - a field that is optional, how to check if an instance has such a connection or not?
I tried to implement the check through the check_child method, but it always returns True
Model:

class Category(models.Model):
    LEVELS = [(i, str(i)) for i in range(1, 4)]
    name = models.CharField(verbose_name='Название', max_length=160, unique=True)
    parent = models.ForeignKey('self', related_name='child', null=True, blank=True)
    title = models.CharField(verbose_name='Заголовок', max_length=260)
    slug = models.SlugField(verbose_name='ЧПУ', max_length=60, unique=True, allow_unicode=True)
    level = models.IntegerField(verbose_name='Уровень', choices=LEVELS)

    def check_child(self):
        if not self.child is None:
            return True
        return False

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question