1

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?

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.