【问题标题】:How can I order by a method in django REST?如何通过 django REST 中的方法订购?
【发布时间】: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


    【解决方案1】:

    您可以使用使用Concat 的注释来获取父类别名称与该注释的名称和顺序连接

    from django.db.models.functions import Concat
    categories_ordered = Category.objects.annotate(
        joined=Concat('parent_category__name', 'name')
    ).order_by('joined')
    

    如果类别的深度超过 2 个级别,我不确定这将如何表现

    【讨论】:

    • 我可以在哪里尝试,在模型中?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多