我正在使用Django pgcrypto 字段来加密模型中的金额值,
Invoice
如下所示:
from pgcrypto import fields
class Invoice(models.Model):
# Some other fields
amount_usd = fields.TextPGPSymmetricKeyField(default='')
objects = InvoicePGPManager() # Manager used for PGP Fields
我使用 a 是TextPGPSymmetricKeyField
因为我必须将值存储为浮点数并且django-pgcrypto-fields
没有 FloatField 的等价物。
现在我需要amount_usd
通过 API 传递这个值,并且我必须将小数限制为两位。
我尝试过使用以下内容:
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?