是否可以在类似于 intcomma
的注释中格式化 DecimalField
模板标签?
class Product(models.Model):
plu = models.CharField(max_length=8)
description = models.CharField(max_length=255)
price = models.DecimalField(max_digits=9, decimal_places=2, default=D('0'))
例如,如果instance.price = Decimal('1000')
,带注释的属性将返回使用逗号分隔符格式化的数字 (1,000.00
)
我正在 ReportLab 中创建 PDF 报告,表数据是列表的列表。如果查询集可以返回逗号分隔的数字,则会提高速度,而不必遍历查询集中的每个对象来应用格式。
from django.contrib.humanize.templatetags.humanize import intcomma
products = Product.objects.all()
table_data = [['PLU', 'Description', 'Price']]
for product in products:
table_data.append([product.plu, product.description, intcomma(product.price)])
可以简化为
table_data = [['PLU', 'Description', 'Price']] + list(
Product.objects.all()
.annotate(comma_sep_price=...)
.values_list('plu', 'descripton', 'comma_sep_price')
)
最佳答案
我能够使用 PostgreSQL data type formatting function TO_CHAR
解决这个问题.
from django.db.models import CharField, ExpressionWrapper, Func, F, Value
data = (
Product.objects
.annotate(
formatted_price=ExpressionWrapper(
Func(F('price'), Value('FM999,999,999.00'), function='TO_CHAR'),
output_field=CharField()
)
)
.values_list('plu', 'description', 'formatted_price')
)
或者作为可重复使用的custom query expression :
class CommaSeparated(Func):
function = 'TO_CHAR'
template = "%(function)s(%(expressions)s, 'FM999,999,999.00')"
data = (
Product.objects
.annotate(formatted_price=CommaSeparated(F('price'), output_field=CharField()))
.values('plu', 'description', 'formatted_price')
)
关于Django在查询/注释中格式化DecimalField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57804643/