On May 22, 7:14 am, KentH <k...@khauser.net> wrote: > I am trying to configure a m2m relationship to be ordered based on data in > the through table. I assumed an 'order' attribute in the through-table's > Meta class would be honored, but it's not. Bug #11850 (closed: wontfix) > relates to this problem, but with no pointer as to a work-around. > > As custom ordering would seem a prime use case for a custom through class > on m2m relations, I'm surprised how hard it is. > > In my case, I'm trying to order digital assets (eg sheet music) into a > number of folios (collections). Music can appear in several collections. > Order is manually specified for each collection. An attribute in a custom > through table is a natural solution, but it doesn't work. > > Other examples which come to mind: Authors and books, or songs and > composers. Since books are alphabetized by lead author, the order matters. > And we wouldn't want Django to list "Lennon & McCartney" songs as "McCartney > & Lennon" > > Anyway, how is the best way to crack this nut? After studying > `db.models.related` I tried building a custom manager on the related class, > and override the `get_query_set` method to look for the through attribute > on the manager to update the ordered_by clause. No luck -- but with > prefetch interaction, this seems pretty fragile in any case. > > Thanks for any help. > > Kent.
So, you would want to do collection.songs.all() and have that ordered by the sequence defined in the m2m table? I agree - this seems to be somewhat hard currently. You would need to do [t.song for t in Through.objects.filter(collection=collection).order_by('seq').select_related('song')] or something like that... It might be nice if the related manager of collection would have a special lookup 'through', so you could to collection.songs.all().select_related('through'), or collection.songs.all().order_by('through__seq'). But it would be somewhat messy to do that currently. Implementing better custom lookups could make this easier to implement. - Anssi -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.