Reputation: 4658
suppose I have three model like this:
class video(models.Model):
name=models.CharField(max_length = 100)
class image(models.Model):
name=models.CharField(max_length = 100)
class comments(models.Model):
content=models.CharField(max_length = 100)
now i want to notic the user if their video or image get an comment
this is what i want
the message model:
class message(models.Model):
type=models.CharField(max_length = 100) # 'video' or 'image'
video_or_image=models.ForeignKey(video or image)
#the type is just a string to tell if the comment is about the video or image
#video_or_image need to be video foreignkey or image foreignkey depends on type
is it possible.
I currently work around this by two method
first:
class message(models.Model):
type = models.CharField(max_length = 100) # 'video' or 'image'
video_or_image_id = models.IntegerField(default = 1)
#
second
class message(models.Model):
type=models.CharField(max_length = 100) # 'video' or 'image'
video=models.ForeignKey(video)
image=models.ForeignKey(image)
# if the comment is about video just leave the image empty
if the one field to multiple model can not be done, then which my work around method is better, or help me with a better one!
Upvotes: 2
Views: 910
Reputation: 18982
You are looking for a GenericForeignKey
.
This is also the way contrib.comments relates comments to commented items.
Upvotes: 6