开发者

Is a Django ManyToMany add() an append function?

开发者 https://www.devze.com 2023-01-11 14:23 出处:网络
If my models.py has a ManyToMany relationship between books and authors, and if for a particular SampleBook I execute:

If my models.py has a ManyToMany relationship between books and authors, and if for a particular SampleBook I execute: Sample_book.a开发者_StackOverflow社区uthors.add(author1) Sample_book.authors.add(author2) Sample_book.authors.add(author3)

are author1, author2, and author3 stored in books.authors.all in the order in which they were added?

i.e. is the ManyToMany add() function similar to an append? If I try to extract the values in a for loop, will they be returned in the order they were initially added?

Continued:

The answer received below stated that the db/ django did not bear responsibility for the order in which the objects were stored.

The problem is that I have a nested sort problem. e.g. I send over a list of books to the template, using order_by to sort it. But the template needs to display all the books, as well as all authors for each book, with the authors sorted as well.

Since there is a ManyToMany relationship between books and authors, the authors for each book are not necessarily stored in order (hence my original question). So the template displays books in the order passed, and I used regroup as a hack to sort the authors retrieved by association from each book.

Does anybody have a more elegant solution?


The relational database makes no guarantee of ordering.

Django can't make a guarantee, either, since it depends on the underlying relational database.

If you want a specific ordering, you must implement that specific ordering by providing some kind of sequence number.


Usually order_by is simplest, Since it's part of the query set. See http://docs.djangoproject.com/en/1.2/ref/models/querysets/#order-by-fields

The fastest way is to create a list and use sorted in the view function.

object_list = sorted( some_query_set, key=lambda o: o.some_field )

Or

object_list= list( some_query_set )
object_list.sort( key=lambda o: o.some_field )

Either of these will be really fast.

0

精彩评论

暂无评论...
验证码 换一张
取 消