[Fixed]-Django Sort ManyToMany Field in A Nonsignificant Order

1👍

The position of a stop is relative to a Route, e.g. one stop can be first for route 1, 2nd for route 2 and etc. So this is a perfect example that you need more metadata about the Route-Stop relation. Djagno solves this by letting you provide a Intermediate Table with two ForeignKey and the metadata you need for the relation.

class Stop(models.Model):
    #...

class Route(models.Model):

    #...

    stops = models.ManyToManyField(Stop, through='RouteStop', blank=True, related_name="routes", verbose_name="Stops")


class RouteStop(models.Model):
    stop = models.ForeignKey(Stop)
    route = models.ForeignKey(Route)
    position = models.PositiveSmallIntegerField()

    class Meta:
        unique_together = (("stop", "route"),)

Now when you get Routes you can order route.stops by RouteStop.position, something like:

Route.objects.all().prefetch_related(
    Prefetch('stops', queryset=Stop.objects.all().order_by('routestop__position'))
)
👤Todor

Leave a comment