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.
答案 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)