'How to declare in Django Models a class with an attribute pointing to the same class?

How can I declare the previous or next attributes pointing to the same class type ?

I couln't find the answer in official documentation

In the models.py below I have just written "scenes" for previous and next

from pickle import TRUE
from django.db import models
from django.contrib.auth.models import User

class scenes(models.Model):
    name = models.CharField('Event name', max_length=120)
    record_date = models.DateTimeField('Event date')
    manager = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL)
    description = models.TextField(blank=True)
    previous = models.ForeignKey(scenes, blank=True, null=True, on_delete=models.SET_NULL)
    next = models.ForeignKey(scenes, blank=True, null=True, on_delete=models.SET_NULL)

    def __str__(self):
        return self.name


Solution 1:[1]

You can use 'self' to refer to the same model. But here you likely can work with a OneToOneField [Django-doc] with next as value for the related_name=… parameter [Django-doc] for the previous field. That way when you set B as the next of A, A is the previous of B automatically:

from pickle import TRUE
from django.db import models
from django.conf import settings

class scenes(models.Model):
    name = models.CharField('Event name', max_length=120)
    record_date = models.DateTimeField('Event date')
    manager = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        blank=True,
        null=True,
        on_delete=models.SET_NULL
    )
    description = models.TextField(blank=True)
    previous = models.OneToOneField(
        'self',
        blank=True,
        null=True,
        related_name='next'
        on_delete=models.SET_NULL
    )

    def __str__(self):
        return self.name

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Willem Van Onsem