获取objects.all()、reverse()或降序
在 Django 中,调用 object.manytomany.all().reverse()
及其等效模板 object.manytomany.all.reverse
似乎不适用于多对多关系。
如何反转多对多关系的结果列表?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可能会犯这个错误,或者我可能误解了您的代码片段。假设您有一个图书模型,其中一本书的实例可以有多个作者。
现在这将返回所有 Book 实例的
QuerySet
-Book.objects.all()
objects
是模型的默认管理器,它是复数。object
在 Python 中是它自己的东西,最好不要将它用作您自己的变量。还值得说明的是,“manytomany”不是 Django 中的字段或函数。让我们知道这是否是您定义的。因此,要获取一本书实例可能拥有的 ManyToMany 多个作者:现在您已经有了作者,并且这些作者采用 QuerySet 的形式,您可以执行任何正常的 QuerySet 操作,包括反转。
请记住,反转未排序的内容并没有多大意义,因此您可能需要考虑使用
objects.order_by("").reverse()
。希望有帮助。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.
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: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.
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.所以你可以这样做
So you can do it as
这可用于根据对象的属性按照我们想要的顺序对对象进行排序。
This can be used to order objects in the order we want according to their properties.
书 = 反转(Book.objects.all())
book = reversed(Book.objects.all())