2010-06-01 78 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