user695652
user695652

Reputation: 4275

django model: have recursive relationship

How would I correctly model a recursive relationship as the one illustrated below?

class A(models.Model):
    previous_A = models.OneToOneField(A)

Upvotes: 1

Views: 2843

Answers (1)

Joseph Victor Zammit
Joseph Victor Zammit

Reputation: 15310

With Django you can model parent-child relationships as follows:

class Person(models.Model):
    name = models.CharField(max_length=128)
    parent = models.ForeignKey('self', null=True, related_name='children')

Quoting the ForeignKey docs:

To create a recursive relationship – an object that has a many-to-one relationship with itself – use models.ForeignKey('self').

P.S. By "reflexive relationship" I assumed you are referring to a recursive association that connects a single class type (serving in one role) to itself (serving in another role); i.e. parent-child relationship.

Upvotes: 6

Related Questions