如何在 ForeignKeyField 中引用自己?

How to refer to oneself in a ForeignKeyField?

我正在尝试创建一个引用同一模型中的另一个对象的外键。

from peewee import *

class Domain(Model):
    owner = CharField(max_length=40)
    resolves_to = CharField(max_length=40)
    name = CharField(max_length=26)
    last_renewal = IntegerField(null=True) # null=True means that it is optional
    ending_date = IntegerField()
    active = BooleanField()
    parent = ForeignKeyField(Domain, null=True)

    class Meta:
        db_table = "domain"

但是我收到一个错误,提示未定义域。

您使用字符串文字 'self',如 documentation on ForeignKeys:

中指定

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

因此您可以通过以下方式实现:

from django.db import models

class Domain(models.Model):
    # …
    parent = models.ForeignKey(<strong>'self'</strong>, null=True, on_delete=models.CASCADE)

    class Meta:
        db_table = 'domain'