Hi all… I can't come up with a syntax to order by a field of the `trough` table in a many to many relationship and how to combine it with `prefetch_related`.
I have two models — _Note_ and _Pinboard_ — with a many to many relationship. Those two models are related trough another model — _Pin_ — so I can store additional information about the relationship. I want to show the related _Note_ instances in the `DetailView` for _Pinboard_. That's not the problem. But I want to __prefetch__ the notes and also __order__ them on the `position` field from the `through` table. Any hints on how to archive this (prefetch + ordering on `trough` table)? # Example This is what I have so far… it works in the sense, that I don't have to query for each entry, but I found no way to order the _Note_ instances by their `position` without more queries for each instance. __Models__ from django.db import models class Note(models.Model): title = models.CharField(max_lenght=200) content = models.TextField() class Pinboard(models.Model): title = models.CharField(max_lenght=200) notes = models.ManyToManyField( Note, blank=True, related_name='pinboards', through='Pin' ) class Pin(models.Model): class Meta: ordering = ['position', ] get_latest_by = 'position' pinboard = models.ForeignKey(Pinboard, related_name='note_pins') note = models.ForeignKey(Note, related_name='pinboard_pins') position = models.PositiveSmallIntegerField(default=0) __View__ from django.views.generic import DetailView class PinboardDetailView(DetailView): model = Pinboard # THIS is the part, where I want the notes ordered by the position in queryset = Pinboard.objects.prefetch_related('notes') __Template__ {% extends 'base.html' %} {% block content %} <h1>{{ pinboard.title }}</h1> {% if pinboard.notes.all.exists %} <ol> {% for note in pinboard.notes %} <li>{{ note.title }}</li> {% endfor %} </ol> {% else %} <p>Nothing here yet…</p> {% endif %} {% endblock content %} # What else did I try Right now I'm using the `Pin` Model for my query (with `select_related`). It's a workaround. I'm thinking there must be a better way, using `Pinboard` and `prefetch_related` seems more straight forward, but I can't figure out how. BTW: It's on SO here: http://stackoverflow.com/questions/35410834/how-to-order-by-a-field-from-the-through-table-for-a-m2m-relationship-in-djang Regards -brutus -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/36d9514c-8415-4589-a221-2169f30acedb%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.