2010-09-06 87 views
0

我用Django創建了一個項目,並試圖從表單寫入數據庫。 模型類有兩類:Django表格完整性錯誤

class Contact(models.Model): 
    name = models.CharField(max_length=200) 
    birth_day = models.DateTimeField() 
    address = models.CharField(max_length=200) 

class PhoneNumber(models.Model): 
    PHONETYPE_CHOICES = (
     (0, 'Home'), 
     (1, 'Work'), 
     (2, 'Fax'), 
     (3, 'Mobile'), 
     (4, 'Other'), 
    ) 
    contact = models.ForeignKey(Contact) 
    phone_type = models.CharField(max_length=255, choices=PHONETYPE_CHOICES) 
    phonenumber = models.CharField(max_length=30) 

現在,如果我想寫這個表單和我只用:

名稱

生日

地址

號碼類型

電話號碼

作爲表單字段。

我得到:

IntegrityError x_phonenumber.contact_id不能爲null

這是視圖的一部分:

def main(request): 
    if request.method == 'POST': 
     form = UserForm(request.POST) 
     if form.is_valid(): 
      name = form.cleaned_data['name'], 
      birth_day = form.cleaned_data['birth_day'], 
      address = form.cleaned_data['address'], 
#   contact1= form.cleaned_data['id'] 
      phone_type = form.cleaned_data['phone_type'] 
      phonenumber = form.cleaned_data['phonenumber'] 
      contact = Contact(
       name = form.cleaned_data['name'], 
       birth_day = form.cleaned_data['birth_day'], 
       address = form.cleaned_data['address'], 
      ) 
      contact.save() 
      number = PhoneNumber(
#    contact1 = form.cleaned_data ['id'] 
       phone_type = form.cleaned_data['phone_type'], 
       phonenumber = form.cleaned_data['phonenumber'], 

      ) 
      number.save() 

我知道我必須填寫的人的ID那個ForeignKey,但我認爲這就是ForeignKey爲我做的。

兩個註釋掉的對象「contact1」不起作用。但是,這基本上是我想要的,添加到這個ID。

此外,Django總是爲每個表(聯繫人和電話號碼)添加一個_id主鍵。

所以我沒有明白爲什麼,Django沒有添加到這個。

我如何保存這與正確的ID數據庫,主鍵等。

感謝

回答

2

除非你告訴它,否則ForeignKey不能神奇地知道它應該指向哪個人。

在你的情況中,一旦你做了contact.save(),你現在的一個Contact實例,所以你可以使用它。

number = PhoneNumber(
    contact = contact, 
    phone_type = form.cleaned_data['phone_type'], 
    phonenumber = form.cleaned_data['phonenumber'], 
) 
number.save() 
0

的Django怎麼知道至極行應該是鏈? 您必須將聯繫實例作爲外鍵字段的參數。

contact = Contact(...) 
contact.save() 
number = PhoneNumber(...) 
number.contact = contact # here comes the instance of Contact model 
number.save() 
1

考慮以下兩行:

number = PhoneNumber(
    # contact1 = form.cleaned_data ['id'] 
    phone_type = form.cleaned_data['phone_type'], 
    phonenumber = form.cleaned_data['phonenumber'], 
) 

number.save() 

你正在創建的PhoneNumber一個實例,並保存它。然而,PhoneNumber的任何實例都需要有一個有效的外鍵給Contact的實例。這並沒有設置在你之前save()PhoneNumber,因此你得到的錯誤。

爲了解決這個問題,請在保存電話號碼之前將PhoneNumber實例的contact字段指向您保存的Contact。類似這樣的:

number = PhoneNumber(
    # contact1 = form.cleaned_data ['id'] 
    phone_type = form.cleaned_data['phone_type'], 
    phonenumber = form.cleaned_data['phonenumber'], 
) 

number.contact = contact # <===== Attach the contact. 
number.save()