我有关系数据库,其中一个关系如下:
Student < --- > Major_enrollments
所以我需要在两个表中创建一个带有外键的列到第二个表。如果我定义了这个类,我怎么能这样做呢?学生首先,我会收到这样的错误通知:“ NameError:名称'Major_enrollments'未定义”。
这是我写的一段代码(models.py):
class Students(models.Model):
nr_album = models.IntegerField()
fName = models.CharField(max_length=70)
lName = models.CharField(max_length=70)
pesel = models.BigIntegerField()
address = models.CharField(max_length=100)
major_enrollments = models.ForeignKey(Major_enrollments) #<---THAT DOESN'T WORK
def __unicode__(self):
return unicode(self.pesel)
class Meta:
db_table='Students'
class Major_enrollments(models.Model):
majors = models.ForeignKey(Majors)
students = models.ForeignKey(Students)
def __unicode__(self):
return unicode(self.id)
class Meta:
db_table='Major_enrollments'
答案 0 :(得分:6)
您可以使用类名(作为字符串)而不是类本身:
class Students(models.Model):
nr_album = models.IntegerField()
fName = models.CharField(max_length=70)
lName = models.CharField(max_length=70)
pesel = models.BigIntegerField()
address = models.CharField(max_length=100)
major_enrollments = models.ForeignKey('Major_enrollments')
def __unicode__(self):
return unicode(self.pesel)
class Meta:
db_table='Students'
答案 1 :(得分:2)
使用文档中描述的具有类名称的字符串:https://docs.djangoproject.com/en/1.5/ref/models/fields/#foreignkey