Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Accessing through ManyToMany extra field in template

I have the following Model Structures :

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']

I have been trying for a while to get the position data (includes in AssocProjectMedia) in my template with the following :

in my view :

project = get_object_or_404(Project, slug=project_slug)
    return render(request, 'projects/projects_details.html', {"project":project})

in my template :

{% for media in project.media_set.all %}
...
{% endfor %}

But this doesn't work, nothing appear.

If instead I write:

{% for media in project.media.all %}
...
{% endfor %}

I will get my media data but not the one included in the through model (AssocProjectMedia).

If anyone has an idea on how to do that...

like image 467
arthurmchr Avatar asked Jul 07 '13 13:07

arthurmchr


1 Answers

Try this:

{% for assoc_media in project.assocprojectmedia_set.all %}
    {{assoc_media.position}}
    {# or whatever field #}
{% endfor %}
like image 96
karthikr Avatar answered Sep 20 '22 20:09

karthikr