django在模型中存储价值

时间:2016-03-15 09:07:52

标签: python django

我如何使用data中的logs model id_information model字段中存储值

# Create your models here.
class information(models.Model):
    id_=models.CharField(max_length=50)
    modelno=models.CharField(max_length=50)

    def __str__(self):
        return self.id_

class logs(models.Model):
    info=models.ForeignKey(information, on_delete=models.CASCADE)
    data = models.TextField(blank=True, null=True)
    updated = models.DateTimeField(auto_now=True)

我试过这个但是失败了

 try:
 obj=information.objects.get(id_=21)   #21 is example id
 obj.logs.create(data=5000)   #need to store 5000
 except:
 print("exception")             #always throwing exception not saving

1 个答案:

答案 0 :(得分:5)

使用

obj.logs_set.create(data=5000) 

或者您应该为字段信息定义 related_name

info=models.ForeignKey(information, on_delete=models.CASCADE,related_name="logs")

然后你可以使用像

obj.logs.create(data=5000)