获得外键的价值

时间:2012-09-30 16:38:56

标签: django foreign-keys

class Sample(models.model):
sampleID = models.AutoField(primary_key=True)
    something = models.IntegerField()
    .
    .
    .

def save(self, *args, **kwargs):
    is_new = self.pk is None
    super(Sample, self).save(*args, **kwargs)
    if is_new:
        alpha = AnotherSample()
        alpha.asampleID =  self.pk
        alpha.say = "Lolz"
        alpha.save()

我无法将主键分配给Sample的AnotherSample引用键。总是说

Cannot assign "1L": "AnotherSample.asampleID" must be a "Sample" instance.

2 个答案:

答案 0 :(得分:1)

来自the docs

  

在幕后,Django将"_id"附加到字段名称以创建其数据库列名。

alpha.asampleID_id = self.pk

这就是为什么后缀为“ID”是不合适的。

答案 1 :(得分:0)

根据给定的错误消息,您似乎正在尝试保存关系。您应该传递实际对象,而不是其主键。

def save(self, *args, **kwargs):
    is_new = self.pk is None
    super(Sample, self).save(*args, **kwargs)
    if is_new:
        alpha = AnotherSample()
        alpha.asampleID =  self
        alpha.say = "Lolz"
        alpha.save()