我如何获得多对多对象的id? 我有三个模型,媒体,图像和幻灯片。 如何通过我的幻灯片对象获取媒体的ID?
class Media(models.Model):
CONTENT_TYPE_CHOICES = (
('photos', _('Photos')),
('videos', _('Videos')),
('audio', _('Audio')),
('Object360', _('360 Object')),
('Object3D', _('3D Object')),
)
source = models.FileField(upload_to='magazine')
filename = models.CharField(max_length=50)
content_type = models.CharField(max_length=10, choices=CONTENT_TYPE_CHOICES)
created = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = _('Media')
verbose_name_plural = _('Media')
class ImageComponent(BaseComponent):
media = models.ForeignKey(Media)
is_embed = models.BooleanField(default=True)
is_slideshow =models.BooleanField(default=False)
def __unicode__(self):
return u'Image Component'
class SlideshowComponent(BaseComponent):
image = models.ManyToManyField(ImageComponent)
is_autoplay = models.BooleanField(default=True)
is_embed = models.BooleanField(default=True)
def __unicode__(self):
return u'Slideshow Component'
在我的view.py中我有:slideshow = SlideshowComponent.objects.all()
在模板中我尝试:
{% for slide in slideshow %}
{{ slide.image.media.id}}
但不起作用..
编辑:如何通过media.id
将view.py中的aceess移动到幻灯片对象答案 0 :(得分:2)
好吧,因为image
是一个ManyToManyField,它链接到许多图像(它应该被称为'images')。所以,你需要遍历它:
{% for slide in slideshow %}
{% for image in slide.image.all %}
{{ image.media.id }}
{% endfor %}
{% endfor %}