KSHMR
KSHMR

Reputation: 809

NameError: [Class] not defined

I intend to create a many-to-one relationship between these two classes:

class Bonds(models.Model):
    types = models.ForeignKey(Types)
    rowid = models.AutoField(primary_key=True)
    bond_id = models.TextField(blank=True)
    end_d = models.DateField(blank=True, null=True)
    intr = models.FloatField(blank=True, null=True)
    base_i = models.FloatField(blank=True, null=True)
    type = models.TextField(blank=True)
    start_d = models.DateField(blank=True, null=True)
    first_id = models.DateField(blank=True, null=True)
    first_pd = models.DateField(blank=True, null=True)
    class Meta:
        managed = True
        db_table = 'bonds'
        in_db = 'bonds'

class Types(models.Model):
    rowid = models.AutoField(primary_key=True)
    type = models.TextField(blank=True)
    cal = models.TextField(blank=True) # This field type is a guess.
    ind = models.TextField(blank=True)
    paypy = models.IntegerField(blank=True, null=True)
    loan_type = models.TextField(blank=True)
    adj_intr_date = models.NullBooleanField()
    class Meta:
        managed = True
        db_table = 'types'
        in_db = 'bonds'

I am running Django inside Apache2. When I try to run this code, an error occurs:

NameError at /: name 'Types' is not defined

Is this not the correct way to define a ForeignKey relationship?

Upvotes: 0

Views: 206

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599630

It is standard in Python that names need to be defined before you can use them. In your case, the Types class is not defined until after the declaration of the types field that references it. You could fix this by swapping the order of the classes, or use a special workaround that Django enables: make the class reference a string:

types = models.ForeignKey('Types')

Upvotes: 3

Related Questions