Django model one foreign key to many tables Django model one foreign key to many tables postgresql postgresql

Django model one foreign key to many tables


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-relationsFor your requirement it could look something like this:

from django.db import modelsfrom django.contrib.contenttypes.fields import GenericForeignKeyfrom django.contrib.contenttypes.models import ContentTypeclass 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">