Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to refer to oneself in a ForeignKeyField?

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading