在Django中,按模型获取自动id字段设置为null = True并且我得到IntegrityError:“可能不为null”

时间:2011-12-30 14:37:58

标签: django django-models

我一直在尝试重置我的数据库并弄清楚为什么会这样,但出于某种原因我收到了这个错误:

IntegrityError: main_funding_rounds_investments.investment_id may not be NULL

我无法弄清楚自动id字段是如何或为何为空?如果有人有想法我会非常感激!

当我用inspectdb检查数据库时,我得到以下内容:

class MainFundingRoundsInvestments(models.Model):
    id = models.IntegerField(primary_key=True)
    funding_rounds_id = models.IntegerField()
    investment_id = models.IntegerField()
    class Meta:
        db_table = u'main_funding_rounds_investments'

class MainInvestment(models.Model):
    id = models.IntegerField(primary_key=True)
    class Meta:
        db_table = u'main_investment'

以下是我的模特:

#funding rounds
class funding_rounds(models.Model):
    funded_day = models.IntegerField(null=True)
investments = models.ManyToManyField("Investment")

class Investment(models.Model):
    company = models.ManyToManyField("Company", null=True, related_name     ="Investments_company")
    financial_org = models.ManyToManyField("Financial_org", null=True, related_name ="Investments_financial_org")
    person = models.ManyToManyField("Person", null=True, related_name ="Investments_person")

这是我创建对象的地方:

def save_dict_to_db_R(model_class ,dicta):

testCo = model_class()

for key,value in dicta.items():
    try:
        field = model_class._meta.get_field(key)

        if isinstance(field, models.ManyToManyField):
            continue
        else:
            if model_class._meta.get_field(key):
                print("i == something:" + key + " ")
                setattr(testCo, key, value)
    except FieldDoesNotExist:
        continue

testCo.save(

for field in model_class._meta.many_to_many:
    if field.name in dicta and hasattr(dicta[field.name], 'append'):
        for obj in dicta[field.name]:
            rel_instance = save_dict_to_db_R(field.rel.to, obj)
            getattr(testCo, field.name).add(rel_instance)

2 个答案:

答案 0 :(得分:1)

为什么要手动设置主键字段?除非你需要调用与id不同的字段,或者赋予它不同的属性,否则你应该将它从模型中删除,让Django自动添加它。

您当前的问题是您使用的是IntegerField而不是AutoField,但是如果您自动删除了您的定义,那将为您完成。

答案 1 :(得分:0)

尝试使用AutoField