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
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:
Note that you don’t need to set/read the
connection_content_typeorconnection_object_idfields yourself… the generics framework will handle that for you, they just need to be there for the generics to work.