【问题标题】:Django: Order object depending in two valuesDjango:订单对象取决于两个值
【发布时间】:2020-09-02 22:48:12
【问题描述】:

所以我有这个:

class Thread(models.Model):
    first_thread_notification = models.IntegerField(default=0)
    second_thread_notification = models.IntegerField(default=0)

我需要根据 2 个对象的总和对对象进行排序:

class Meta:
    ordering = ['-first_thread_notification' + '-second_thread_notification']

我知道这是不正确的,但我该怎么做?

编辑

class ManagerSum(models.Manager):
    Thread.objects.annotate(
       total=ExpressionWrapper(
       F('first_thread_notification') + F('-second_thread_notification'), 
       output_field=IntegerField(),
       )
    ).order_by('-total')

class Thread(models.Model):
    first_thread_notification = models.IntegerField(default=0)
    second_thread_notification = models.IntegerField(default=0)

    total_notifications = ManagerSum()

class Meta:
    ordering = ['-total_notifications']

这对吗?

【问题讨论】:

    标签: python django django-models


    【解决方案1】:

    您可以使用注解sum them via an F expression.

    from django.db.models import IntegerField, ExpressionWrapper
    Thread.objects.annotate(
        total=ExpressionWrapper(
            F('first_thread_notification') + F('-second_thread_notification'), 
            output_field=IntegerField(),
        )
    ).order_by('-total')
    

    【讨论】: