Django在查询/注释中格式化DecimalField

标签 django aggregate django-queryset

是否可以在类似于 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 解决这个问题.

使用ExpressionWrapper :

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/

相关文章:

django - 在单个查询集中获取帖子及其最后评论

Django prefetch_related 与 m2m 通过关系

django - 限制django表单文件上传的文件扩展名

python - Django - 如何在 Django 错误页面中获取 DatabaseError "current transaction is aborted"的调试信息?

django - 如何在AWS ECS docker容器中获取AWS凭证?

delphi - 如何在 TClientDataSet 中使用 BIGINT (TLargeintField) 聚合字段?

python - 如何在 Django 中获取最后 10 项数据?

PostgreSQL 相等聚合

aggregate - Tableau 聚合为值范围的容器

python - 是否可以创建 Django 查询集来执行此复杂查询?