Home > Net >  Django: typehinting backward / related_name / ForeignKey relationships
Django: typehinting backward / related_name / ForeignKey relationships

Time:08-25

Let's say we have the following models:

class Site(models.Model):
    # This is djangos build-in Site Model
    pass

class Organization(models.Model):
    site = models.OneToOneField(Site)

And if I use this somewhere in some other class:

organization = self.site.organization

Then mypy complains:

Site has no attribute "organization"

How can I make mypy happy here?

CodePudding user response:

I just know a litle of english, and i don't know this is true. But you can add

site = models.OneToOneField(Site, on_delete=models.CASCADE)

CodePudding user response:

You need to set the related_name attribute:

class Organization(models.Model):
    site = models.OneToOneField(Site, related_name="organization")
  • Related