Как объявить в Django Models класс с атрибутом, указывающим на тот же класс?

Как я могу объявить предыдущий или следующий атрибуты, указывающие на один и тот же тип класса?

Я не смог найти ответ в официальной документации

В приведенном ниже models.py я просто написал "scenes" для previous и 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

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.

Вернуться на верх