Want one Like button shared by posts, comments and photos, without creating a separate like table for each model? Use GenericForeignKey from django.contrib.contenttypes: a single Like table points at any model through the pair content_type and object_id. This fits projects where many content types share one feature — like, bookmark, tagging — and you want to add a new model without changing the schema.

The Problem

A plain ForeignKey points at exactly one model. To like both posts and comments, you’d need PostLike, CommentLike, PhotoLike… Each table repeats the user and created_at columns. Every new content type means a new table plus a pile of duplicated code. Merging them into one table with an object_type string column loses every ORM benefit: you can’t fetch the real object, and you can’t filter backwards.

# The manual way: one like table per model, duplicated code
class PostLike(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
class CommentLike(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
comment = models.ForeignKey(Comment, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)

The Solution

GenericForeignKey is not a real column in the database. It’s a “bridge” that reads from two real columns: content_type (which model this is) and object_id (the record’s primary key). One Like table serves every model, while GenericRelation sits on the liked model for reverse queries.

# models.py
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.db import models
class Like(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveBigIntegerField()
content_object = GenericForeignKey("content_type", "object_id")
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
indexes = [models.Index(fields=["content_type", "object_id"])]
class Post(models.Model):
title = models.CharField(max_length=200)
likes = GenericRelation(Like, related_query_name="post")
class Comment(models.Model):
body = models.TextField()
likes = GenericRelation(Like, related_query_name="comment")

Create a like through content_object, count backwards through GenericRelation:

# Create a like: just like a normal ForeignKey
Like.objects.create(user=request.user, content_object=post)
Like.objects.create(user=request.user, content_object=comment)
# Count a post's likes without knowing the table
post.likes.count()
# Filter likes for one object: filter by content_type + object_id,
# NEVER filter directly on content_object (it raises an error)
ct = ContentType.objects.get_for_model(Post)
Like.objects.filter(content_type=ct, object_id=post.pk)
# related_query_name enables reverse filtering from the Like side
Like.objects.filter(post__title__contains="Django")

Three important notes. First, Django doesn’t create an index for GenericForeignKey by itself, so add Meta.indexes for the (content_type, object_id) pair yourself — otherwise the Like table slows down as it grows. Second, on delete: with GenericRelation, deleting a post deletes its likes too; without it, the like rows stay but content_object returns None, and you have to clean them up with a signal or a periodic task. Third, GenericForeignKey doesn’t appear in ModelForm and can’t be used directly in filter(), so put like-creation logic in a view or service, not in a form.

Apply It to Your Project

This pattern works right away for any “attach to anything” feature: like, bookmark, report abuse, tagging. Add a new model — say Video — and one line, likes = GenericRelation(Like), is all it takes, no extra table migration. But if the project has only one or two models that need likes, a plain ForeignKey is still better: clearer, with a real database constraint, faster JOINs and easier to read. Use GenericForeignKey only when “shared by every model” is a real requirement, not because it looks tidy.

Related Posts

FAQ

Does GenericForeignKey create a real foreign-key constraint in the database?

No. Only two real columns exist: content_type (a foreign key to the ContentType table) and object_id (an integer). The database can’t guarantee the target record still exists, so handle the case where content_object returns None because the original object was deleted.

How do I filter the Likes of one post correctly?

Filter by the content_type and object_id pair: get the ContentType with ContentType.objects.get_for_model(Post), then Like.objects.filter(content_type=ct, object_id=post.pk). Writing filter(content_object=post) raises an error because GenericForeignKey is not a real field.

What happens to a post’s Likes when the post is deleted?

If the model has a GenericRelation, Django deletes the likes along with it, like a ForeignKey cascade. Without it, the like rows stay orphaned and content_object returns None. To avoid junk, either add a GenericRelation, or clean up with a pre_delete signal or a periodic task.

When should I not use GenericForeignKey?

When only one or two models need likes, or when you need fast JOINs and integrity enforced at the database layer. A ForeignKey is clearer and faster, and the database protects it. GenericForeignKey is only worth it when the feature genuinely has to be shared across models you don’t know in advance.

💬 Have you tried this in your own project? If you hit an error or have a shorter way, leave a comment below — I read them all and will fold the good ideas into the post.

References

Django documentation — The contenttypes framework: https://docs.djangoproject.com/en/5.2/ref/contrib/contenttypes/