Search code examples
djangogeneric-foreign-key

In Django, do I need to add a db_index to object_id when using a GenericForeignKey?


Django's sample code at https://docs.djangoproject.com/es/1.9/ref/contrib/contenttypes/

content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')

shows object_id without db_index=True

although object_id probably will be used for join operation.

Is db_index=True assumed because of some hidden code regarding GFK? Or should I include it when I need it?


Solution

  • Yes, you should make the object_id field indexable by yourself. As of 1.9, Django doesn't do any magic on that.