Home > Software engineering >  How to refer to oneself in a ForeignKeyField?
How to refer to oneself in a ForeignKeyField?

Time:06-03

I'm trying to create a foreignkey that refers to another object in the same model.

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"

but I get an error that Domain is not defined. Any help is much appreciated, thanks!

CodePudding user response:

You use the string literal 'self', as is specified in the 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).

You thus can implement this with:

from django.db import models

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

    class Meta:
        db_table = 'domain'
  • Related