2个Django型号主键和外键

2024-04-24 03:46:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要设置一个带有主键和外键的模型。第二种型号也一样。在

默认情况下,第一个型号的主键是tcu_đid:

class Tcu(models.Model):
    imei = models.CharField(max_length=30, unique=True)

第二个模型的主键设置为True,tcu模型的外键为:

^{pr2}$

这很好用,但是当我尝试向第一个模型添加外键时,问题就出现了:

 class Tcu(models.Model):
        imei = models.CharField(max_length=30, unique=True)
        phone_num = models.ForeignKey(Sim, null=True, blank=True)

tcu电话号码=模型.ForeignKey(Sim卡) 名称错误:未定义名称“Sim”


Tags: 模型truemodelmodelssimlengthmax外键
1条回答
网友
1楼 · 发布于 2024-04-24 03:46:56

Django documentation for the ForeignKey field声明:

If you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the model object itself.

所以在你的情况下,应该是:

class Tcu(models.Model):
    imei = models.CharField(max_length=30, unique=True)
    phone_num = models.ForeignKey('Sim', blank = True)

class Sim(models.Model):
    phone_num = models.CharField(max_length=30, primary_key=True)
    tcu = models.ForeignKey(Tcu, null=True, blank=True)

相关问题 更多 >