Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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_length=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

like image 578
John Avatar asked Jun 01 '10 12:06

John


1 Answers

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()
like image 75
Jarret Hardie Avatar answered Oct 22 '22 09:10

Jarret Hardie