2011-11-30 76 views
0

我正在與這兩個(示範)車型Django項目數據庫並將租戶與公寓而不是建築聯繫起來。因此,我現在計劃遷移到以下三種模式:ForeignKey的關係和遷移在Django

Tenant: id, Aparment(ForeignKey), User(ForeignKey), NameOfTenant(CharacterField) 

Apartment: id, Building(ForeignKey), RoomNumber(Interger), Address(CharacterField) 

Building: id, DateWhenItWasBuild(Date) 

首先,我增加了單元模型/桌,並與來自建築物表(地址和建築物的外鍵)的信息來填充它。其次,我將公寓的外鍵字段添加到租戶模型。

如果我現在要引用的租戶表公寓ID的公寓(這反過來引用到大樓),我得到一個外鍵約束的例外:

(1452, 'Cannot add or update a child row: a foreign key constraint fails 
(`database`.`tenant_tenant`, CONSTRAINT `apartment_id_refs_id_5dfbfc78bb68defd` 
FOREIGN KEY (`apartment_id`) REFERENCES `property_apartment` (`id`))') 

我不太清楚爲什麼會發生這種情況,但我懷疑它可能導致以下問題: Tentant擁有建築外鍵和公寓外鍵。然而,公寓也有建築的外鍵。

在接下來的步驟中,我會在租戶中添加參考到公寓,然後刪除對建築物的參考。這裏的問題是,我不能先刪除建築物參考,然後添加公寓參考,因爲我會失去住房建築/公寓的信息。

有沒有人有一個想法,如果這是問題,還是我錯過了完全不同的東西?

回答

1

第一種方法:

您可以創建樹表和在遷移完成rename tables到原來的名字:

Create table new_building (id, DateWhenItWasBuild(Date)); 
insert into new_building (id, DateWhenItWasBuil) 
select (id, DateWhenItWasBuil) from building; 

Create table Apartment (id, Building(ForeignKey), 
RoomNumber(Interger), Address(CharacterField) ; 

insert into Apartment (id, Building(ForeignKey), 
RoomNumber(Interger), Address(CharacterField)) 
select id, id, NULL, Address from building; 

create table new_Tenant(id, Aparment(ForeignKey), 
User(ForeignKey), NameOfTenant(CharacterField)); 

insert into new_Tenant (id, Aparment, 
User, NameOfTenant) 
select id, building, user, nameofTenant) 

然後刪除舊錶,並重新命名新聞:

DROP TABEL Tenant; 
DROP TABLE building; 
RENAME TABLE new_Tenant TO Tenant 
    , new_building TO building; 

我認爲在這一點上apparmentId是buildingId。但是你可以從另一個表中取這個值。

請記住,手動創建表不是強制性的。您可以在元重命名錶的名稱,並執行syncdb創建表:

class Tenant(models.Model):  
    # ... 
    class Meta: 
     db_Table = 'new_tenant' 

另外,還可以用滴出刪除外鍵字段外鍵約束。

[ALTER TABLE tenant_tenant DROP FOREIGN KEY apartment_id_refs_id_5dfbfc78bb68defd;][2] 

記住south可以幫助您在這個問題上。

+0

我試圖找出爲什麼會發生這種情況,似乎上述關係問題不是原因。 – phoxley