开发者

django inheritance with foreignkey field

My models are set up as follows (this is an example and not my actual models)

class modelA(Model):
   field1 = CharField(max_len开发者_Python百科gth=50)

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

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

Would I be able to have an connection to modelB stored in anotherModel since modelB inherits from model A.

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

If not how would I handle this?

Thanks


The Generic Relations feature from Django's built-in ContentTypes module is the most supported way to handle polymorphic foreign keys.

You will need to add some supporting fields to your model so that the framework can figure out which particular class a foreign key represents, but other than that it will handle loading the correct type fairly transparently.

In your case, it would be something like:

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')

Note that you don't need to set/read the connection_content_type or connection_object_id fields yourself... the generics framework will handle that for you, they just need to be there for the generics to work.

mod_a = modelA()
mod_b = modelB()

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


Yes, you can do that. If you add a ForeignKey in "anotherModel" to modelB and try running syncdb it will bark at you saying that you need to specify a "related_name". So, on one (or both) of your ForeignKey fields add a related_name attribute.

You should also read through this: http://docs.djangoproject.com/en/dev/topics/db/models/#be-careful-with-related-name to get some more info about related_name.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜