user13788524
user13788524

Reputation:

Add a foreign key to AbstractUser

I have this two models:

class User(AbstractUser):
    pass



class Listing(models.Model):
    listing_id = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')
    title = models.CharField(max_length=64)
    owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="listing")

I would like to do the following in the User model:

class User(AbstractUser):
    listing = models.ForeignKey(Listing, on_delete=models.CASCADE)

But i'm getting the following error: NameError: name 'Listing' is not defined

Is it possible to add a foreign key to abstractuser?

Upvotes: 1

Views: 765

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

Since you define User before Listing, the name is not yet defined. This is however not a problem for Django since you can use a string literal as well:

class User(AbstractUser):
    listing = models.ForeignKey('Listing', on_delete=models.CASCADE)

class Listing(models.Model):
    listing_id = models.AutoField(
        auto_created=True,
        primary_key=True,
        serialize=False,
        verbose_name='ID'
    )
    title = models.CharField(max_length=64)
    owner = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='listing'
    )

You can however not define a ForeignKey with the name listing here, since you already have an ForeignKey in your Listing model with as related_name='listing'. This would thus result in an error. You thus should either change the related_name, or rename the listing in the User model.

Upvotes: 1

Iain Shelvington
Iain Shelvington

Reputation: 32244

Pass the model name as a string to avoid issues where you want to reference a model that is not yet defined

class User(AbstractUser):
    listing = models.ForeignKey('Listing', on_delete=models.CASCADE)

You can also use the same method to refer to a model in another app by adding the app name

listing = models.ForeignKey('app.Listing', on_delete=models.CASCADE)

Upvotes: 0

Related Questions