【发布时间】:2021-07-13 04:39:19
【问题描述】:
我有一个简单的模型,如下所示:
class Category(models.Model):
"""Class to represent the category of an Item. Like plants, bikes..."""
name = models.TextField()
description = models.TextField(null=True)
color = models.TextField(null=True)
parent_category = models.ForeignKey(
'self',
on_delete=models.SET_NULL,
null=True,
)
class Meta: # pylint: disable=too-few-public-methods
"""Class to represent metadata of the object."""
# ordering = ['category_name'] <------- I WOULD LIKE THIS SORTING
ordering = ['parent_category__name', 'name']
def category_name(self):
"""String for representing the Model object."""
if self.parent_category:
return str(self.parent_category.category_name() + " -> " + self.name)
我无法找到解决方案来按模型内部的方法进行排序,例如示例模型中注释掉的示例。
我在不同步骤中使用的两个过滤器的结果没有给 mt 我想要的结果-
如果我有:
Music/Guitar
Music/Piano
Music
Books
它会返回:
Music/Guitar
Music/Piano
Books
Music
而我需要的是:
Books
Music
Music/Guitar
Music/Piano
也可以在序列化程序中使用它,或者能够使用 REST 查询中的参数选择排序,但我无法做到这一点。
【问题讨论】:
标签: python django sorting django-models django-rest-framework