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']
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.
- [Django]-Django models: how to overcome 'through' ManyToMany option limitation
- [Django]-Django custom form ImportError even though file is in the same directory
- [Django]-Django admin โ OneToOneField inline throws "has no ForeignKey" exception
- [Django]-What is exactly Meta in Django?
- [Django]-Django render not working when redirected from another view