2010-06-01 77 views
6

我的模型設置如下Django的繼承(這是一個例子,而不是我的實際型號)與外鍵字段

class modelA(Model): 
    field1 = CharField(max_length=50) 

class modelB(modelA): 
    field2 = CharField(max_length=50) 

class anotherModel(Model): 
    connection = models.ForeignKey(modelA) 
    title = CharField(max_length=50) 

請問我能因爲modelB從繼承到具有存儲在anotherModel到modelB的連接模型A.

mod_b = modelB() 
conn_b = anotherModel() 
conn_b.connection = mod_b 

如果不是我該如何處理?

感謝

回答

4

Django內置的Generic Relations featureContentTypes模塊是處理多態外鍵最受支持的方式。

您將需要一些配套的字段添加到您的模型,使框架可以找出哪些特定類的外鍵代表,但比它要處理加載正確的類型相當透明等。

在你的情況,這將是這樣的:

from django.contrib.contenttypes.models import ContentType 
from django.contrib.contenttypes import generic 

# modelA and modelB as before 

class anotherModel(Model): 
    connection_content_type = models.ForeignKey(ContentType) 
    connection_object_id = models.PositiveIntegerField() 
    connection = generic.GenericForeignKey('connection_content_type', 
     'connection_object_id') 

注意,你不需要設置/讀取connection_content_typeconnection_object_id領域自己......仿製藥框架會處理,對於你,他們只需要在那裏爲仿製藥工作。

mod_a = modelA() 
mod_b = modelB() 

conn = anotherModel() 
conn.connection = mod_b 
conn.save() 
conn.connection = mod_a # change your mind 
conn.save() 
0

是的,你可以做到這一點。如果您在「anotherModel」中將ForeignKey添加到modelB並嘗試運行syncdb,它會對您說,您需要指定「related_name」。因此,在一個(或兩個)ForeignKey字段中添加一個related_name屬性。

你也應該通過這個閱讀:http://docs.djangoproject.com/en/dev/topics/db/models/#be-careful-with-related-name,以獲取有關related_name一些更多的信息。

+0

syncdb只在模型定義級別捕獲錯誤 - 然而約翰想知道他是否可以以某種方式應用他的定義 – Geradeausanwalt 2010-08-05 06:14:50