[Answered ]-Django model foreign key to one in a list of models

1👍

In Django, you cannot directly create a ForeignKey to multiple models. However, you can achieve a similar effect by using generic relations. In your case, you can use Django’s GenericForeignKey to create a relationship between the Profile model and both CustomUser and Shipper models.

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

class Profile(models.Model):
    # Your other fields in the Profile model

    # GenericForeignKey fields
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')
from django.contrib.contenttypes.fields import GenericRelation

class CustomUser(models.Model):
    # Your fields in the CustomUser model
    profiles = GenericRelation(Profile)

class Shipper(models.Model):
    # Your fields in the Shipper model
    profiles = GenericRelation(Profile)

now you can query for each type like this

# Get all profiles associated with CustomUser
custom_user_profiles = Profile.objects.filter(content_type__model='customuser')

# Get all profiles associated with Shipper
shipper_profiles = Profile.objects.filter(content_type__model='shipper')

Leave a comment