Django order_by 关于自定义模型方法
Django order_by on custom model method
我有以下型号:
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')
但意识到我有不同货币的特殊情况
例如:
IN 数据库:
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()
模型方法是我在使用 order_by()
方法时寻找的方法,但似乎 order_by
不支持自定义模型方法。
有没有一种方法可以使用自定义模型方法在查询中进行排序?
您可以 annotate
amount_convert
和 order_by
的输出应该是什么。像这样:
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')
我有以下型号:
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')
但意识到我有不同货币的特殊情况
例如:
IN 数据库:
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()
模型方法是我在使用 order_by()
方法时寻找的方法,但似乎 order_by
不支持自定义模型方法。
有没有一种方法可以使用自定义模型方法在查询中进行排序?
您可以 annotate
amount_convert
和 order_by
的输出应该是什么。像这样:
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')