如何在 Django 模型中声明一个 class 并且属性指向相同的 class?

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

如何声明指向相同 class 类型的上一个或下一个属性?

我在official documentation

中找不到答案

在下面的 models.py 中,我刚刚为 previousnext

写了“场景”
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

您可以使用'self'来引用相同的模型。但在这里您可能可以使用 OneToOneField [Django-doc] with next as value for the related_name=… parameter [Django-doc] 作为 previous 字段。这样,当您将 B 设置为 Anext 时,A 就是 previousB 自动:

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.<strong>OneToOneField(</strong>
        <strong>'self'</strong>,
        blank=True,
        null=True,
        <strong>related_name='next'</strong>
        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.