Inheriting django with foreignkey field

My models are configured as follows (this is an example, 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) 

Can I have a connection to modelB stored in another module, since modelB inherits from model A.

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

If I could not handle it?

thanks

+6
django django-models
source share
2 answers

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 # 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 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 # change your mind conn.save() 
+4
source share

Yes you can do it. If you add ForeignKey to "anotherModel" in modelB and try to run syncdb, you will be clear that you need to specify "related_name". So, on one (or both) of your ForeignKey fields, add the related_name attribute.

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

0
source share

All Articles