[Django]-Django displaying many to many in template โ€“ ordering ignored?

3๐Ÿ‘

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']
๐Ÿ‘คCyril N.

0๐Ÿ‘

This is an oddity of Django, when using a ManyToManyField, if the through model provides a Meta.ordering it is not automatically applied to the resulting QuerySet for related items.

You can apply it manually, in your example

@register.filter
def order_by(queryset, args):
    args = [x.strip() for x in args.split(',')]
    return queryset.order_by(*args)


{% for image in page.gallery.images.all|order_by:"galleryimage__position" %}

You can also use a modified ManyToManyField called SortedManyToManyField available https://github.com/django-ordered-model/django-ordered-model/blob/67bbc3a707202d4e201411284df0ca222255d3c7/ordered_model/fields.py which has the benefit of not having to repeat the ordering โ€“ it is read directly from the Meta.

๐Ÿ‘คshuckc

Leave a comment