简体   繁体   English

如何通过 django REST 中的方法订购?

[英]How can I order by a method in django REST?

I have a simple model like the following:我有一个简单的 model ,如下所示:

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)

I have not been able to find a solution to sort by a method inside the model like the example that is commented out in the example model.我无法找到一个解决方案来通过 model 中的方法进行排序,就像示例 model 中注释掉的示例一样。

The results that the two filters I'm using in different steps don't give mt the results I want-我在不同步骤中使用的两个过滤器的结果没有给 mt 我想要的结果-

If I have:如果我有:

Music/Guitar
Music/Piano
Music
Books

It will return:它将返回:

Music/Guitar
Music/Piano
Books
Music

And what I need is:我需要的是:

Books
Music
Music/Guitar
Music/Piano

It would also be ok to have this in the serializer or be able to choosse the sorting with the parameters in the REST query, but I have not been able to make this work in any possibility.也可以在序列化程序中使用它,或者能够使用 REST 查询中的参数选择排序,但我无法以任何可能的方式完成这项工作。

You can use an annotation that uses Concat to get the parent category name concatenated with name and order by that annotation您可以使用使用Concat的注释来获取父类别名称与该注释的名称和顺序连接

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

I'm not sure how this will behave if the categories are more than 2 levels deep如果类别深度超过 2 个级别,我不确定这将如何表现

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM