Rawisara Lohanimit
Rawisara Lohanimit

Reputation: 13

Django - can we make a model inherit itself?

I wonder whether we can make a model that have a child inheriting the same class like:

class A(models.Model):
    #something
class B(models.Model):
    parent = models.ForeignKey(A, on_delete=models.CASCADE)
    #and some B will have class B as a child

Upvotes: 0

Views: 145

Answers (1)

Tim Nyborg
Tim Nyborg

Reputation: 1649

Yes, that's a self-referential or recursive model:

class B(models.Model):
    ...
    child = models.ForeignKey('B', ... )

The key is to put the referenced model in quotes, which lets Django get around the issue of referring to a model before it's defined.

Another option is to use self instead, again in quotes:

    child = models.ForeignKey('self', ... )

Upvotes: 1

Related Questions