Getting objects.all() reverse() or descending order

gabor picture gabor · Feb 20, 2012 · Viewed 9.9k times · Source

In Django, calling object.manytomany.all().reverse(), and its template equivalent, object.manytomany.all.reverse, don't seem to work for many-to-many relationships.

How do I reverse a list of results of a many-to-many relationship?

Answer

JCotton picture JCotton · Feb 20, 2012

You may be going about this wrong or maybe I misunderstand your code snippet. Say you have a Book Model where an instance of a Book can have multiple authors.

class Author(models.Model):
  ...

class Book(models.Model):
  authors = models.ManyToManyField(Author)

Now this will return a QuerySet of all Book instances - Book.objects.all()

objects is the default manager for a Model and it's plural. object is its own thing in Python and it's best not to use it as your own variable. It's also worth stating that "manytomany" isn't a field or function in Django. Let us know if that's something you defined. So to get the ManyToMany multiple authors a book instance might have:

book = Book.objects.all()[0]
type(book.authors)  # tells you this is a ManyRelatedManager
type(book.authors.all()) # tells you this is a QuerySet
book.authors.all()  # will print out the authors for this book

Now that you have the authors and those authors are in the form of a QuerySet, you can do any normal QuerySet manipulation including reversing.

book.authors.all().reverse()

Remember that reversing something that isn't ordered doesn't mean much so you may want to consider using objects.order_by("<field name>").reverse(). Hope that helps.