Search code examples
djangoforeign-keys

Django foreign key relationship with multiple models


I have many different models with different types of fields. I want to use foreign key for multiple models. Like:

class Model1(models.Model):
    title = models.TextField()
    body = models.TextField()
    
class Model2(models.Model):
    tag = models.CharField(max_length=200)
    uploadedDate = models.DateTimeField(auto_now_add=True)
    
class MainModel(models.Model):
    
    content = models.ForeignKey([Model1, Model2], on_delete=models.CASCADE) # this will give error

How can I do this?


Solution

  • models.py

    from django.contrib.contenttypes.models import ContentType
    from django.contrib.contenttypes.fields import GenericForeignKey
    
    class MainModel(models.Model):
        
        target_ct = models.ForeignKey(ContentType,
        related_name='target_obj', on_delete=models.CASCADE)
        target_id = models.PositiveIntegerField()
        target = GenericForeignKey('target_ct', 'target_id')
    

    now from your main model you can access any model you want.
    To use it let us say you have an instance like this.

    model1 = Model1.objects.first() 
    

    to pass this to your MainModel you can just do something like this.

       MainModel.objects.create(target=model1)