🎸 Django Intermediate

What is Django content types framework?

Answer

Django's contenttypes framework enables generic relationships — a ForeignKey that can point to any model. Useful for: likes/reactions that work on any content type, activity feeds, comments on multiple models, tags. ContentType model: stores information about all installed models (app_label, model). from django.contrib.contenttypes.models import ContentType ct = ContentType.objects.get_for_model(Article) # or: ct = ContentType.objects.get(app_label="blog", model="article") model_class = ct.model_class() # returns Article class. Generic FK in model: from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey("content_type", "object_id") class Meta: unique_together = [["user", "content_type", "object_id"]] indexes = [models.Index(fields=["content_type", "object_id"])]. Reverse relations on the liked model: class Article(models.Model): ... likes = GenericRelation(Like, related_query_name="article"). Usage: Like.objects.create(user=user, content_object=article) article.likes.all() user_likes_article = Like.objects.filter(user=user, content_object=article).exists(). Prefetching generic relations: Article.objects.prefetch_related("likes"). Useful for building Instagram-style hearts or Reddit-style upvotes on multiple content types.