2

对于这种情况,我想QuerySet按升序排序:

PRIORITY_CHOICES = (
(1, "P1"),
(2, "P2"),
(3, "P3"),
(4, "P4"),
(5, "P5"),
)

class Task(models.Model):
     name = models.CharField(max_length=255)
     priority = models.PositiveIntegerField(choices=PRIORITY_CHOICES)

现在,因为优先级可以接受 None 值。当我在我的视图代码中执行此操作时,问题在于订购查询集:

task_list = Task.objects.all().order_by("priority")

这将返回查询集,其中对象按优先级升序排列,无值在前。我想要升序列表,但我想在最后包含 None 值。我有一个庞大的数据库,所以我有兴趣在数据库级别完成此任务。

4

3 回答 3

3

这可能是您最好的选择。

import itertools
q = itertools.chain(
        Task.objects.filter(priority__isnull=False).order_by("priority"),
        Task.objects.filter(priority__isnull=True))
# Then you can iterate over your custom order
result = [(x.name, x.priority) for x in q]
于 2012-08-02T01:38:06.667 回答
1

您可以使用(添加“-”符号)将顺序更改为降序queryset.order_by('-field'),但在 Django 中没有办法告诉空值应该如何排序 - 这是数据库特定的行为。如果使用降序排序仍然首先在数据库中为您提供空值 - use queryset.extra(select={'order': 'custom_sql_function(priority)'}).order_by('order'),如果custom_sql_function字段为空,则将字段转换为整数,并且特定于您的数据库引擎。为了获得更快的性能,您可以在function(field).

于 2012-08-02T01:33:39.600 回答
0

你可以在这样的模型中简单地做到这一点

class ModelName(models.Model):
    feild_1 = models.CharField( max_length=150)
    feild_2 = models.CharField( max_length=150, blank=True, null=True)

    class Meta:
        ordering = [F('order').asc(nulls_last=True)]
于 2021-12-15T14:38:45.847 回答