ordering queryset by a through field

hey, I have those classes:

class CatalogImage(models.Model):
    title = models.CharField(max_length=120, verbose_name=_("title"))
    description = models.TextField(verbose_name=_("description"))
    image = models.ImageField(verbose_name=_("image"))

class CatalogAlbum(models.Model):
    title = models.CharField(max_length=120, verbose_name=_("title"))
    slug = models.SlugField(max_length=120, verbose_name=_("slug"), unique=True)
    images = models.ManyToManyField(to=CatalogImage, related_name='images', null=True, blank=True, through='ThroughImage')# 

class ThroughImage(models.Model):
    catalogImage = models.ForeignKey(CatalogImage, on_delete=models.CASCADE)
    catalogAlbum = models.ForeignKey(CatalogAlbum, on_delete=models.CASCADE)
    weight = models.IntegerField(verbose_name=_("weight"), unique=True)

    class Meta:
        ordering = ('weight',)

I use the ThroughImage as a through to CatalogAlbum.images so that every CatalogImage connected to a CatalogAlbum has an integer for keeping order.

but I did not understand how can I order by weight in the views.
I tried this without success:

def catalog_page(request, *args, **kwargs):
    from catalogAlbum.models import CatalogAlbum
    slug = kwargs['slug']
    album = get_object_or_404(CatalogAlbum.objects.prefetch_related('images'), slug=slug)
    if album:
        album.images.order_by('throughimage__weight')
    return render(request, 'catalog_page.html', {'album':album})

where is my mistake?

Hi!

The order_by seems fine to me. Have you tried inverting the order with a minus sign to see if it’s modified?

hey, thank you for your replay.
I’m not sure in what line you mean it. but no I did not test any -ordering.
I manage to solve my problem with those changes the the catalog_page view:

def catalog_page(request, *args, **kwargs):
    from catalogAlbum.models import CatalogAlbum
    slug = kwargs['slug']
    album = get_object_or_404(CatalogAlbum.objects.prefetch_related('images'), slug=slug)
    ret = {'album_title': album.title,
            'images': album.images.values().order_by('throughimage__weight'),
    }
    return render(request, 'catalog_page.html', {'context':ret})

I have to make some changes to catalog_page.html to work with the new represented data. And it seems to work this way, although I am not using the built-in ordering in the meta.
I’m not sure why calling the values and then orver_by works for me but it is.
I would love to hear any comments on how to improve this code

Sorry, I should have provided some example of the negative ordering.
Anyway, I meant to invert the order like this.

album.images.order_by('-throughimage__weight')

I just tried in a project of mine and per the documentation, order_by is prioritized over ordering in model’s Meta.

Glad to know you solved it!