所以我有這個: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')
添加回答
舉報
0/150
提交
取消