Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python django模型字段如何与多个模型关联?_Python_Django_Model_Meta - Fatal编程技术网

Python django模型字段如何与多个模型关联?

Python django模型字段如何与多个模型关联?,python,django,model,meta,Python,Django,Model,Meta,假设我有三个这样的模型: 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) 现在我

假设我有三个这样的模型:

 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)
现在我想提醒用户,如果他们的视频或图像得到评论

这就是我想要的

消息模型:

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
有可能吗

我目前通过两种方法来解决这个问题

首先

   class message(models.Model):
       type = models.CharField(max_length = 100) # 'video' or 'image'
       video_or_image_id = models.IntegerField(default = 1)
       # 

  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
如果一个字段到多个模型不能做到,那么我的变通方法是哪一种更好,还是帮我找一种更好的

您正在寻找一个新的解决方案

这也是关联项目的方式