Skip to content
thesarfo

Note

Generic Relationships

The three pieces needed for a generic relationship in Django — Content Type, Object Id, and Content Object — with Tag and Like examples.

views 0

There are three things we need to specify a generic relationship in Django. Content Type, Object Id and Content Object.

Content type is the type of content eg: video, product, article etc. Object Id is the Id associated with the object. Content object is the object instance of the content type.

In our new app called Tags we do this in it’s models.py

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
# Create your models here.
class Tag(models.Model):
label = models.CharField(max_length=255)
class TaggedItem(models.Model):
'''what tag applies to what object'''
tag = models.ForeignKey(Tag, on_delete=models.CASCADE)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey()

Lets create a new app called likes, and establish a generic relationship with the user based on what the user likes. Remember the three things that you need to establish a generic relationship are above.

from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
# Create your models here.
class LikedItem(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()