Django contenttypes documentation
Simpleisbetterthancomplex blog on content types
Using ContentType enables truly generic relationships between models.
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
class TaggedItem(models.Model):
tag = models.SlugField()
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
def __str__(self):
return self.tag
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
class Bookmark(models.Model):
url = models.URLField()
tags = GenericRelation(TaggedItem, related_query_name='bookmark')
>>> TaggedItem.objects.filter(bookmark__url__contains='django')
It does add an extra layer, which can slow down the process of the application.
One way to avoid this behavior is manual filtering, instead of defining a GenericRelation.
Activity.objects.create(content_object=comment, activity_type=Activity.LIKE, user=request.user)
// in views.py
from django.contrib.contenttypes.models import ContentType
# Pass the instance we created in the snippet above
ct = ContentType.objects.get_for_model(comment)
# Get the list of likes
Activity.objects.filter(content_type=ct, object_id=comment.id, activity_type=Activity.LIKE)