django admin - 模型交叉引用 - 外部和多对多关系 - 在管理员中显示

时间:2015-02-06 04:58:09

标签: django django-models django-admin

我在同一个应用程序中有2个模型相互引用。一个作为外键,另一个作为多个键。

class VideoEmbed(models.Model):
    person = models.ForeignKey('Person')
    title = models.CharField(max_length=250) 
    video = EmbedVideoField()

class Person(models.Model):
    name = models.CharField(max_length=200)
    born = models.DateField(blank=True, null=True)
    video = models.ManyToManyField(VideoEmbed, related_name='video_embed', null=True, blank=True)

我想这样做的原因是将Person与其相关视频相关联,因为一个人可能有很多视频。现在在django管理站点中,videoembed模型将针对每个人录制视频,因此这些将分别显示在Person的每个实例中。但是在django站点中,我必须从多个选择框中选择每个视频。许多关系领域。

Video field in Person instance

我希望此字段仅显示通过videoembed模型链接到此实例的视频,而不是所有添加的视频。有没有办法做到这一点?如果没有,那么我可以在本节中看到2个字段而不是一个,这样我就可以选择链接到Person实例的视频。

1 个答案:

答案 0 :(得分:1)

我认为这是对how ManyToMany relationships work的误解。定义ManyToMany时,反向关系包含在" far side"关系。

例如,考虑代码的精简版本:

class Video(models.Model):
    title = models.CharField(max_length=250) 

class Person(models.Model):
    name = models.CharField(max_length=200)
    videos = models.ManyToManyField(VideoEmbed, related_name='people', null=True, blank=True)

在此,person_object.videos为一个人提供了一组视频,显而易见的是,Django还在Video上设置了可访问的video_object.people的反向关系}这是一组通过Person关系引用特定Video的所有ManyToMany个对象。

此关系默认为model_name_set,因此对于您的关系,默认值为person_set,但在related_name中设置ManytoManyField参数它会覆盖这个。

ForeignKey模型添加Video会创建and entirely separate and independent relationship

考虑这个简单的模型,Video现在有一个作者,人们被标记在视频中(实际上他们可能都会看到视频,但我们正在展示ForeignKey和ManyToMany是如何独立的,以及属性名称的良好语义值:

class Video(models.Model):
    title = models.CharField(max_length=250) 
    author = models.ForeignKey('Person')

class Person(models.Model):
    name = models.CharField(max_length=200)
    videos_person_tagged_in = models.ManyToManyField(VideoEmbed, related_name='tagged_people', null=True, blank=True)

此处,设置video_object.author不会更改视频的tagged_people,也不会为某个人设置videos_person_tagged_in更改作者。

至于reverse relation for a ManyToMany isn't showing up in Django admin, this is a known issue requires custom forms to work around的原因。主要是因为您在一个项目上定义了ManyToMany,它只会显示在该模型管理页面中。

相关问题