bencunningham
bencunningham

Reputation: 356

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?

Upvotes: 9

Views: 3673

Answers (2)

solarissmoke
solarissmoke

Reputation: 31404

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.

Upvotes: 11

Jason Lee Eaton
Jason Lee Eaton

Reputation: 178

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()

Upvotes: 2

Related Questions