Django ContentTypes Framework

JunePyo Suh·2020년 9월 22일
0

Django contenttypes documentation
Simpleisbetterthancomplex blog on content types

Generic relations

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

Reverse generic relations

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')

Caveats with reverse generic relations

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)

0개의 댓글