简体   繁体   中英

Django order_by on custom model method

I have the following 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

Because transaction may contain different currency, each currency has different decimal value

I tried to use the query Transactions.objects.filter(...).order_by('-transaction_amount') but realized I have special case with different currencies

For example:

IN DB:

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

Should id=1 be on top of id=2 but the transaction_amount I'm querying is wrong.

So the amount_convert() model method is what I'm looking for when using order_by() method, but it seems like order_by doesn't support custom model method. Is there a way I can use custom model method for sorting in the query?

You can annotate what should be the output of amount_convert and order_by it. Like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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