Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 652
gabor Avatar asked Feb 20 '12 02:02

gabor


2 Answers

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.

like image 52
JCotton Avatar answered Nov 14 '22 08:11

JCotton


So you can do it as

object.manytomany.order_by("-id")
like image 2
Shubham Agrawal Avatar answered Nov 14 '22 10:11

Shubham Agrawal