Irfan Harun
Irfan Harun

Reputation: 1059

use record from same model as foreignkey in django

my model is as follows :

class Profile(model.Models):
    name = models.CharField(max_length = 20)
    full_name  = models.CharField(max_length = 20)
    husband_spouse = models.ForeignKey(Profile, on_delete=models.CASCADE)

on doing python manage.py makemigrations I get the following error : NameError: name 'Profile' is not defined

Question : How should I use another record of the same model as a foreignkey in my current model

TIA

Upvotes: 1

Views: 21

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476614

This is because at that point Profile is not yet defined, you can use a string literal 'self' in that case:

class Profile(model.Models):
    name = models.CharField(max_length=20)
    full_name  = models.CharField(max_length=20)
    husband_spouse = models.ForeignKey(
        'self',
        on_delete=models.CASCADE
    )

Upvotes: 2

Related Questions