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