执行 Django Queryset 上的 Python

huangapple go评论50阅读模式
英文:

Execute python on Django Queryset

问题

以下是翻译的内容:

有没有办法在Django Queryset上执行Python代码?

我将数据存储在数据库中作为字节,我想将它们转换为“B”、“KB”、“MB”、“GB”、“TB”、“PB”、“EB”、“ZB”、“YB”。是否有办法在传递到视图之前将它们转换?

def get_context_data(self, *args, **kwargs):
    context = super().get_context_data(*args, **kwargs)

    context['user'] = (
        DataVolume.objects.values('user')
        .order_by('user')
        .annotate(imgs=Sum('imgs'), 
                  size=SumConvertBytes('user_bytes'),
        )
    )

注意:代码部分没有进行中文翻译,只提供了原文。

英文:

Is there a way to execute python code on a Django Queryset?

I am storing data in the db as bytes and I want to convert them to "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB". Is there any way I can convert the them before passing to the view?

def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
 
        context['user'] = (
           DataVolume.objects.values('user')
            .order_by('user')
            .annotate(  imgs=Sum('imgs'), 
                        size=SumConvertBytes('user_bytes'),
                        ),
        )

答案1

得分: 2

格式化不应该放在查询集中,而是应该放在模板中。Django已经有**|filesizeformat**模板过滤器&nbsp;<sup>[Django-doc]</sup>

在查询集中,你只需简单地求和,在模板中你用以下方式渲染:

<pre><code>{{ size<b>|filesizeformat</b> }}</code></pre>

英文:

Formatting does not belong in the queryset, but in the template. Django already has the |filesizeformat template filter&nbsp;<sup>[Django-doc]</sup>:

In the queryset you thus simply sum, and in the template you render with:

<pre><code>{{ size<b>|filesizeformat</b> }}</code></pre>

huangapple
  • 本文由 发表于 2023年4月6日 21:15:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75949967.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定