Django many-to-one relationship: NOT NULL constraint failed

时间:2015-05-24 21:55:42

标签: django

I'm trying to add data to many-to-one relationship tables.

# models.py
class Exp(models.Model):
    name = models.CharField(max_length=20)

class Analysis(models.Model):
    run = models.ForeignKey(Run)


# my_management_command.py
experiment = Exp(name='sss')
analysis = Analysis(run=experiment)
analysis.save()

It works fine in the admin page, but in my management command it fails upon attempt to save:

django.db.utils.IntegrityError: NOT NULL constraint failed: webint_analysis.exp_id

Why is it complaining about the id and how to fix that? Note that I deleted my db to ensure that this is NOT related to migration.

1 个答案:

答案 0 :(得分:1)

当您尝试在Exp对象创建中使用它时,您的Analysis对象没有数据库ID。您应该先保存第一个对象然后再使用它。

您可以执行以下操作

experiment = Exp(name='sss')
experiment.save()
analysis = Analysis(run=experiment)
analysis.save()

或者您可以使用以下

experiment = Exp.objects.create(name="sss")
analysis = Analysis.objects.create(run=experiment)