2011-12-30 28 views
0

我一直在試圖重置我的數據庫並找出爲什麼會發生這種情況,但由於某種原因我得到這個錯誤:在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) 

回答

0

使用AutoField

+0

它由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

+0

由Django添加的主鍵在數據庫,是的。 'AutoField'只是Python包裝器,它表示使用Django模型時的自動遞增字段。此外,['inspectdb'](https://docs.djangoproject.com/en/dev/ref/django-admin/#inspectdb)無法猜測模型字段上需要什麼包裝,因此它使用'IntegerField'作爲因爲這是數據庫的外觀。 – 2012-01-02 14:47:37

1

爲什麼你手動設置主鍵字段試試?除非您需要調用與id不同的字段,或者給它賦予不同的屬性,否則應該將它放在模型之外,並讓Django自動添加它。

您的直接問題是您已經使用IntegerField而不是AutoField,但是如果您自動刪除了您的定義,那麼將爲您完成。

+0

嗨,我的問題中的第一個模型定義不是我的模型,這是我運行「manage.py inspectdb」時得到的。我讓Django自動添加'id'。我想知道爲什麼它不是AutoField,但它應該是。謝謝! – Riku 2012-01-02 07:08:39

相關問題