我有以下模型结构:
class Project(models.Model):
title = models.CharField(max_length = 100)
publish = models.BooleanField()
cover = models.ForeignKey(GenericMedia, related_name='+')
media = models.ManyToManyField(GenericMedia, through='AssocProjectMedia')
credits = models.ManyToManyField(AssocTitleName)
class GenericMedia(models.Model):
limit = models.Q(model = 'Image') | models.Q(model = 'Other')
content_type = models.ForeignKey(ContentType, limit_choices_to = limit)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
def __unicode__(self):
return u"%s" % os.path.basename(self.content_object.url.name)
def instance(self):
return self.content_object.__class__.__name__
class AssocProjectMedia(models.Model):
project = models.ForeignKey(Project)
media = models.ForeignKey(GenericMedia)
position = models.PositiveSmallIntegerField()
grid_size = models.PositiveSmallIntegerField(null = True, blank = True)
class Meta:
ordering = ['position']
我一直试图通过以下方式在我的模板中获取位置数据(包括在AssocProjectMedia中):
在我看来:
project = get_object_or_404(Project, slug=project_slug)
return render(request, 'projects/projects_details.html', {"project":project})
在我的模板中:
{% for media in project.media_set.all %}
...
{% endfor %}
但是这不起作用,没有出现。
如果我写了:
{% for media in project.media.all %}
...
{% endfor %}
我将获取我的媒体数据,但不会获得直通模型中包含的媒体数据(AssocProjectMedia)。
如果有人知道如何做到这一点......
答案 0 :(得分:13)
试试这个:
{% for assoc_media in project.assocprojectmedia_set.all %}
{{assoc_media.position}}
{# or whatever field #}
{% endfor %}