[Django]-Django model one foreign key to many tables

31👍

You should use the contentypes framework in Django.

There’s an example for a generic relation here :https://docs.djangoproject.com/en/1.8/ref/contrib/contenttypes/#generic-relations
For your requirement it could look something like this:

from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType

class Status(models.Model):
    request_type = models.ForeignKey(ContentType)
    request_id = models.PositiveIntegerField()
    request = GenericForeignKey('request_type', 'request_id')

You can then do something like following:

status1 = Status(request=Request1("foo"))
status1.save()
status2 = Status(request=Request2("bar"))
status2.save()

status1.request // <Request1 "foo">
status2.request // <Request2 "bar">

Leave a comment