Avoid Django’s GenericForeignKey

submited by
Style Pass
2021-07-05 17:30:03

In Django, a GenericForeignKey is a feature that allows a model to be related to any other model in the system, as opposed to a ForeignKey which is related to a specific one.

This post is about why GenericForeignKey is usually something you should stay away from. I haven’t see any other articles describing why that is, or what the alternatives are, so this is my attempt at “GenericForeignKey considered harmful”.

Before I get going, I think that there are some legitimate cases, where most of the problems I’ll highlight below aren’t an issue. In particular, the following spring to mind:

However, I think there are many situations that don’t fit the above, but where people are tempted to use GenericForeignKey:

Most of this post is focused on the first of these situations, but I’ll also address the second briefly. First, to make things easier to talk about, I’ll introduce an example application.

Leave a Comment