Django displaying many to many in template - ordering ignored?
I am trying to display a list of objects (Images)based on a many-to-many relationship (Image / Gallery with an intermediary Galleryimage model).
Galleryimage has an additional field called position which I want to use to manage the order that the images are listed in a template.
I also have a page model which can optionally have a gallery attached to it.
My models look like this:
class Page(models.Model):
gallery = models.ForeignKey(Gallery, blank=True, null=True)
slug = models.SlugField()
title = models.CharField(max_length=200)
content = models.TextField()
def __unicode__(self):
return self.title
class Image(models.Model):
title = models.CharField(max_length=50)
image = models.ImageField(upload_to='images')
def __unicode__(self):
return self.title
class Gallery(models.Model):
title = models.CharField(max_length=50)
images = models.ManyToManyField(Image, through='Galleryimage')
def __unicode__(self):
return self.title
class Galleryimage(models.Model):
image = models.ForeignKey(Image)
gallery = models.ForeignKey(Gallery)
position = models.IntegerField()
class Meta:
ordering = ['position']
I am retrieving a page model in my view like this:
def detail(request, page_id):
p = get_object_or_404(Page, pk=page_id)
return render_to_response('detail.html', {'page': p},
context_instance=RequestContext(request))
And finally, I am displaying the images in the template like so:
{% block images %}
{% if page.gallery %}
{% for image in page.gallery.images.all %}
<a rel="gallery" href="{{ STATIC_URL }}{{ image.image }}"></a>
{% endfor %}
{% endif %}
{% endblock %}
The images all display as expected however, the order always seems to be the same, regardless of what I do.
Can anyone give me a nudge in the right direction?
Any a开发者_StackOverflow社区dvice appreciated.
Thanks.
Have you tried to set the ordering option in the Image model? I know you setted the position in the through relation table, but by moving it to the Image model (if possible ?) and setting the order on that model, it shall work.
class Image(models.Model):
title = models.CharField(max_length=50)
image = models.ImageField(upload_to='images')
position = models.IntegerField()
def __unicode__(self):
return self.title
class Meta:
ordering = ['position']
精彩评论