为了账号安全,请及时绑定邮箱和手机立即绑定

Django:订单对象取决于两个值

Django:订单对象取决于两个值

喵喔喔 2023-07-11 17:08:00
所以我有这个:class Thread(models.Model):    first_thread_notification = models.IntegerField(default=0)    second_thread_notification = models.IntegerField(default=0)我需要根据两个对象的总和对对象进行排序: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']它是否正确?
查看完整描述

1 回答

?
温温酱

TA贡献1752条经验 获得超4个赞

您可以使用 annotate通过 F 表达式对它们求和。

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')


查看完整回答
反对 回复 2023-07-11
  • 1 回答
  • 0 关注
  • 76 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信