2015-12-16 190 views
0

我需要使用主键和外键来设置模型。与第二个模型相同。2 django模型主键和外键

第一模型具有默认tcu_id设置为主键:

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

第二模型具有主键设置为True,并且从该组模型的外键:

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

这是工作不错,但现在的问题是当我试图将一个外键添加到第一种模式:

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

在TCU PHONE_NUM = models.ForeignKey(SIM) NameError:名字 '辛' 没有定义

+0

您是否已经导入模型Sim? – Balas

+2

我无法真正理解你为什么要在这里的两个方向FKs。这没有意义。 Sim和Tcu之间关系的实际性质是什么? –

+0

你真是太棒了!谢谢你!我正在测试我的本地主机上的一些功能 – picador

回答

3

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)