繁体   English   中英

Django order_by 自定义 model 方法

[英]Django order_by on custom model method

我有以下 model:

class Transactions(models.Model):
     transaction_amount = models.DecimalField(max_digits=65, decimal_places=0, default=0)
     decimals = models.PositiveSmallIntegerField("Decimals", null=True, blank=True)

     def amount_convert(self):
        try:
            converted = transaction_amount / pow(10, decimals)
        except Exception:
            return None

因为交易可能包含不同的货币,每种货币都有不同的十进制值

我尝试使用查询Transactions.objects.filter(...).order_by('-transaction_amount')但意识到我有不同货币的特殊情况

例如:

在数据库中:

id=1, transaction_amount = 200000, decimals = 4 => amount_convert() = 20 
id=2, transaction_amount = 10000000, decimals = 6 => amount_convert() = 10 

id=1是否应该在id=2之上,但我查询的transaction_amount是错误的。

所以amount_convert() model 方法是我在使用order_by()方法时正在寻找的方法,但似乎order_by不支持自定义 model 方法。 有没有办法可以使用自定义 model 方法在查询中进行排序?

您可以annotate什么应该是amount_convertorder_by的 output 。 像这样:

from django.db.models import F, FloatField

transactions = Transactions.objects.annotate(
        converted_amount=ExpressionWrapper(
            F('transaction_amount')/pow(10, F('decimals')),
            output_field=FloatField()
        )
    ).order_by('-converted_amount')

暂无
暂无

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

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