1

我有关系数据库,其中一个关系如下所示:

Student < --- > Major_enrollments

所以我需要为两个表中的第二个表创建一个带有外键的列。鉴于这样一个事实,如果我首先定义类,例如 Student,我该怎么做,我会收到这样的错误通知:“ NameError: name 'Major_enrollments' is not defined ”。

这是我写的一段代码(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'
4

2 回答 2

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'
于 2013-04-27T12:21:18.620 回答
2

使用带有文档中描述的类名称的字符串:https ://docs.djangoproject.com/en/1.5/ref/models/fields/#foreignkey

于 2013-04-27T12:23:17.967 回答