我一直在試圖重置我的數據庫並找出爲什麼會發生這種情況,但由於某種原因我得到這個錯誤:在Django中,按模型將自動ID字段設置爲null = True,並且我得到IntegrityError:「可能不爲null」
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)
它由Django自動設置。我認爲AutoField實際上是一個IntegerField?文檔:[主鍵](https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.Field.primary_key) – Riku 2012-01-02 07:24:38
由Django添加的主鍵在數據庫,是的。 'AutoField'只是Python包裝器,它表示使用Django模型時的自動遞增字段。此外,['inspectdb'](https://docs.djangoproject.com/en/dev/ref/django-admin/#inspectdb)無法猜測模型字段上需要什麼包裝,因此它使用'IntegerField'作爲因爲這是數據庫的外觀。 – 2012-01-02 14:47:37