Reputation: 1253
I want to associate a model with multiple other possible models in Django.
For example, say I have a model called UploadedImage
, which is just an image that was uploaded by the user. There are many places where a user could upload an image, let's say he could upload it into a project and a comment, so I would also have a Project
and a Comment
model.
Say I want to associate any given UploadedImage
with either a project or a comment. Is there some way to do that?
If I'd just wanted to associate it with one model or the other, I'd put down a foreign key inside the UploadedImage
model, like this,
project = models.ForeignKey('Project')
or
comment = models.ForeignKey('Comment')
But what if I wanted it to remain flexible and able to link to either one?
Back in the C/C++ days I suppose it'd just be a generic pointer and some kind of an enumeration that tells me what the pointer is. What would it be in Django / Python?
The only thing I can think of is just go put in two foreign keys in there plus another variable telling it which is the one that's active, which would work but seems "inelegant".
Any suggestions appreciated. Thanks!!
Upvotes: 0
Views: 138
Reputation: 4355
You can leverage the Django Content Type framework to accomplish exactly what you need.
See generic relations in Django documentation.
Upvotes: 2