I have n classes and each class contains a column called key like this (where n==3)
class class1(models.Model): Id1 = models.AutoField(primary_key=True) key = models.CharField(max_length = 16, blank=True) class class2(models.Model): Id2 = models.AutoField(primary_key=True) key = models.CharField(max_length = 16, blank=True) class class3(models.Model): Id3 = models.AutoField(primary_key=True) key = models.CharField(max_length = 16, blank=True)
I want to make the column key as Foreign key between all the n classes? I know how make a foreign key between 2 classes but I want to do that with many classes because I have about 40 classes and some classes has some commun columns
Advertisement
Answer
You can use generic relations to make a Foreign Key to a generic model. You need to use the ContentType
framework, write your models like:
from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models class class1(models.Model): Id1 = models.AutoField(primary_key=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') class class2(models.Model): Id2 = models.AutoField(primary_key=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id')
Then when you create a class1
instance, you could make a Foreign Key to a class2
(or another model) instance with:
class1_instance = class1.objects.create(content_object=class2.objects.get(id2=1))
Then you can access the class2
instance with:
class1_instance.content_object