【问题标题】:Django - Annotate and cast an encrypted TextField to a FloatField to 2 decimal placesDjango - 将加密的 TextField 注释并转换为 FloatField 到小数点后 2 位
【发布时间】:2019-02-23 11:15:03
【问题描述】:

我正在使用Django pgcrypto fields 加密模型中的金额值 Invoice如下:

from pgcrypto import fields

class Invoice(models.Model):
    # Some other fields
    amount_usd = fields.TextPGPSymmetricKeyField(default='')

    objects = InvoicePGPManager()  # Manager used for PGP Fields

我使用的是TextPGPSymmetricKeyField,因为我必须将值存储为浮点数,而django-pgcrypto-fields 没有与 FloatField 等效的值。

现在我需要通过 API 传递这个 amount_usd 值,并且我必须将小数点限制在两位以内。

我尝试过使用以下方法:

Invoice.objects.all().values('amount_usd').annotate(
    amount_to_float=Cast('amount_usd', FloatField())
)

但这会产生错误,因为字节(加密数据)无法转换为浮点数。

我也试过用这个:

from django.db.models import Func

class Round(Func):
    function = 'ROUND'
    template='%(function)s(%(expressions)s, 2)'


Invoice.objects.all().annotate(PGPSymmetricKeyAggregate(
            'amount_usd')).annotate(amount=Cast(
            'amount_usd__decrypted', FloatField())).annotate(
            amount_final = Round('amount'))

我收到以下错误:

django.db.utils.ProgrammingError: function round(double precision, integer) does not exist
LINE 1: ...sd, 'ultrasecret')::double precision AS "amount", ROUND(pgp_...
                                                         ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

有没有办法将加密字段转换为最多 2 位小数的 FloatField?

【问题讨论】:

    标签: django postgresql django-models django-postgresql pgcrypto


    【解决方案1】:

    你的错误是:double precision AS "amount" 那是因为您将amount_usd 转换为FloatField,后者在SQL 中转换为双精度。

    尝试使用 DecimalField(在 SQL 中转换为数字类型)及其参数。

    Invoices.objects.all().annotate(amount=Cast(
        PGPSymmetricKeyAggregate('amount_usd'),
        DecimalField(max_digits=20, decimal_places=2)))
    

    在此处查看文档:Django DecimalField

    【讨论】:

      猜你喜欢
      • 2014-07-07
      • 1970-01-01
      • 2012-02-05
      • 2021-11-30
      • 2021-09-23
      • 2014-09-08
      • 1970-01-01
      • 2012-03-22
      • 1970-01-01
      相关资源
      最近更新 更多