[Django]-Django – use same column for two foreign keys

0👍

Django content type framework would do the trick

in your case:

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

class Channel(models.Model):
    owner_ct = models.ForeignKey(to=ContentType, on_delete=models.CASCADE, blank=True, null=True) # foreign key table indicator (User,Profile) in your case
    owner_content = models.CharField(max_length=64, blank=True, null=True) # uuid(foreign key) will be placed here as string
    owner_object = GenericForeignKey('owner_ct', 'owner_content') # bridge to object

class User(models.Model):
    channels = GenericRelation(to='Channel', object_id_field='owner_content', content_type_field='owner_ct',related_query_name='channels') # User.channels will be available

class Profile(models.Model):
    channels = GenericRelation(to='Channel', object_id_field='owner_content', content_type_field='owner_ct',related_query_name='channels') # Profile.channels will be available
    

Leave a comment