Understanding ‘GenericForeignKey’ in Django

class Ticket(models.Model):
name = models.CharField(max_length=200, verbose_name=_("name"))
slug = models.SlugField(max_length=250, null=False, blank=True, verbose_name=_("slug"))
class Project(models.Model):
name = models.CharField(max_length=200, verbose_name=_("name"))
slug = models.SlugField(max_length=250, null=False, blank=True, verbose_name=_("slug"))
class User(models.Model):
name = models.CharField(max_length=200, verbose_name=_("name"))
slug = models.SlugField(max_length=250, null=False, blank=True, verbose_name=_("slug"))
class Timeline(models.Model):
involved_object = *****
event_type = models.CharField(max_length=250, default="created")

Using ‘GenericForeignKey’:

class Timeline(models.Model):
content_type = models.ForeignKey(ContentType, related_name="content_type_timelines")
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
event_type = models.CharField(max_length=250, default="created")
t1 = TimeLine(content_object=project_object)
t1.save()
TimeLine.objects.filter(content_object=project_object)
# This will also fail
TimeLine.objects.get(content_object=project_object)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store