Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ForeignKey with multiple models

If I have two models

class modelA(models.Model):
    # properties...

class modelB(models.Model):
    # properties

and I want both models to an images field, then how would I write the image model? If it was just one then I think it would be like:

class Image(models.Model):
   image = models.ForeignKey(modelA)

So if I also wanted modelB to have images, then how would that work? Would I have to write ImageA and ImageB?

like image 615
bencunningham Avatar asked May 11 '16 02:05

bencunningham


2 Answers

Looks like you want to use generic foreign keys:

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

class Image(models.Model):
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

Now your Image model can have foreign keys to either of your other models, and you can have multiple images associated with each object. The documentation I have linked to above explains how to use this setup and query objects etc.

See this answer for how you can limit this so that you can foreign key to only specific models.

like image 143
solarissmoke Avatar answered Oct 06 '22 23:10

solarissmoke


Go the other way with the relationship.

class Image(models.Model):
    # properties

class modelA(models.Model):
    image = models.ForeignKey(Image, vars=vals)

class modelB(models.Model):
    image = models.ForeignKey(Image, vars=vals)

You can then query as

modelB.image
modelA.image

image.modelA_set.all()
image.modelB_set.all()
like image 33
Jason Lee Eaton Avatar answered Oct 06 '22 21:10

Jason Lee Eaton