我打算在这两个类之间创建多对一关系:
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'
我在Apache2中运行Django。当我尝试运行此代码时,会发生错误:
NameError at /: name 'Types' is not defined
这不是定义ForeignKey关系的正确方法吗?
答案 0 :(得分:3)
Python中的标准是在使用它们之前需要定义名称。在您的情况下,Types
类在声明引用它的types
字段之后才定义。您可以通过交换类的顺序来解决这个问题,或者使用Django启用的特殊解决方法:使类引用为字符串:
types = models.ForeignKey('Types')