Generic Foreign Keys in Django

Using content types for generic foreign keys in Django models

May 4, 2014, 5:13 p.m.

Sometimes it is necessary to use a generic foreign key in a Django model class instead of a foreign key to a specific model. One example could be a photo model that you would like to use for a profile model and a event model in some kind of social networking app. Django provides this functionality through its content types framework. There are several steps necessary to use this framework. First you must import the package:

from django.contrib.contenttypes.models import ContentType

Next you must create a dictionary so that the content types framework can know which models to limit your generic foreign key to:

profile_or_event = {'app_label__in': ('myapp',), 'model__in': ('profile', 'event', ), }

Finally you must add 3 fields into the model in which you wish to have the generic foreign key:

content_type = models.ForeignKey(ContentType, limit_choices_to=profile_or_event)
object_id = models.PositiveIntegerField()
profie_event = generic.GenericForeignKey()

Each of these fields are necessary in order to use the generic foreign keys. Now your model will have a foreign key that is usable just like any other, but it is generic to a profile or an event. It is even possible to use the Django admin with these generic foreign keys by simply importing the GenericTabularInline:

from django.contrib.contenttypes.generic import GenericTabularInline

and using it just like any other TabluarInline. This should get you started thinking with generic foreign keys and help you to use DRY (Don't Repeat Yourself) principles.

Comments about Generic Foreign Keys in Django

No one has left a comment yet, be the first to voice your opinion on Generic Foreign Keys in Django!