The shared relationship function from the ContentTypes Django built-in module is the most supported way to handle polymorphic foreign keys.
You will need to add some auxiliary fields to your model so that the structure can determine which class is the foreign key, but in addition it will handle the correct type quite transparently.
In your case, it will be something like:
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic
Note that you do not need to set / read the connection_content_type or connection_object_id fields yourself ... the generics framework will handle this for you, they just have 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
Jarret hardie
source share