gpt4 book ai didi

python - Django:分配尚未创建的类的外键

转载 作者:太空宇宙 更新时间:2023-11-04 07:21:49 25 4
gpt4 key购买 nike

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

Student < --- > Major_enrollments

所以我需要在两个表中创建一个带有第二个表外键的列。鉴于事实,如果我定义类,例如首先是学生,我会收到这样的错误通知:“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'

最佳答案

您可以使用类名(作为字符串)而不是类本身:

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'

关于python - Django:分配尚未创建的类的外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16252035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com