Vepa Orazov
Vepa Orazov

Reputation: 39

how to avoid 'This field is required' when ForeignKey is set to 'self'?

class Category(models.Model):
    name = models.CharField(max_length=50)
    parent_category = models.ForeingKey('self', on_delete=models.CASCADE)

So when I am trying to create a new category in admin panel, django says "This field is required' and highlights parent_category: select field. How to " explain" django, that it is the parent category and therefore no need to select parent_category?

please help.

Upvotes: 1

Views: 187

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477160

If a ForeignKey is optional, you can make it NULLable. So then you insert NULL/None if a Category has no parent:

class Category(models.Model):
    name = models.CharField(max_length=50)
    parent_category = models.ForeignKey(
        'self',
        on_delete=models.CASCADE,
        null=True,
        blank=True
    )

Upvotes: 1

Related Questions