python / intermediate
Snippet
Django Generic Relations with ContentType
Generic relations allow a model to relate to any other model without hardcoded foreign keys. ContentType tracks all models, and GenericForeignKey dynamically resolves the target at runtime.
snippet.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from django.db import modelsfrom django.contrib.contenttypes.models import ContentTypefrom django.contrib.contenttypes.fields import GenericForeignKeyclass Comment(models.Model):content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)object_id = models.PositiveIntegerField()content_object = GenericForeignKey('content_type', 'object_id')text = models.TextField()created_at = models.DateTimeField(auto_now_add=True)# Usage:class Author(models.Model):name = models.CharField(max_length=100)class Book(models.Model):title = models.CharField(max_length=200)# Comments can attach to any model:Comment.objects.create(content_object=author_instance, text='Great author!')Comment.objects.create(content_object=book_instance, text='Excellent read!')
django
Breakdown
1
ContentType
Special model that stores all application models
2
GenericForeignKey
Dynamically links to any model instance
3
content_object=author_instance
Attach comment to any model without changing Comment schema