简体   繁体   English

在Django中删除前导零

[英]Remove leading zeros in Django

I'm displaying data from my MySQL database. 我正在显示来自MySQL数据库的数据。 I would like to remove the leading zeros in a certain fields(the ops and obp fields), only when the value to the left of the decimal point is a 0. If the digit(s) to the left of the decimal point is not 0, then I obviously want that displayed. 我只想删除某些字段( opsobp字段)中的前导零, 当小数点左侧的值是0时。如果小数点左侧的数字不是0,那么我显然希望显示它。

For instance, 例如,

  • 0.750 becomes .750 0.750变成.750

  • 1.000 stays as is 1.000保持原样

I suspect this can be done in when calling the data using django template or in the views.py. 我怀疑这可以在使用django模板或在views.py中调用数据时完成。 How would I do either one? 我该怎么办?

Any help on this would be greatly appreicated! 任何帮助,将不胜感激! Thank You. 谢谢。

views.py views.py

from django.shortcuts import render
from .models import BattingRegStd


# Create your views here.
def batting(request):
    battingregstd2018 = BattingRegStd.objects.filter(year=2018)
    return render(request, 'playerstats/battingReg2018.html', {'battingregstd2018':battingregstd2018})

models.py models.py

class BattingRegStd(models.Model):
    id = models.IntegerField(db_column='ID', primary_key=True)  # Field name made lowercase. 
    obp = models.FloatField(db_column='OBP', blank=True, null=True)  # Field name made lowercase.
    ops = models.FloatField(db_column='OPS', blank=True, null=True)  # Field name made lowercase.
    tb = models.IntegerField(db_column='TB', blank=True, null=True)  # Field name made lowercase.

HTML HTML

{% extends "base.html" %} 

{% block contents %}
<div>
    <table>
        <thead>
            <tr>
                <th>OBP</th>
                <th>OPS</th>
                <th>TB</th>
            </tr>
        </thead>
        <tbody>
            {% for index in battingregstd2018%}
                <td>{{ index.obp}}</td>
                <td>{{ index.ops}}</td>
                <td>{{ index.tb}}</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</div>
{% endblock %}

You can use 您可以使用

def batting_avg_format(num):
    numstr = str(num)
    if numstr[0]!='0':
        return numstr
    else:
        return numstr[1:]

Either incorporate it as a method on your BattingRegStd Model and apply it, or directly do a list comprehension after you have filtered the model but before your render your HTML. 可以将其作为您的BattingRegStd模型的一种方法并应用它,或者在过滤模型之后但呈现HTML之前直接进行列表理解。 The advantage of incorporating it as a model method is that you can now call it from the template, as long as the only parameter in your method is self . 将其合并为模型方法的优点是,现在您可以从模板中调用它,只要方法中的唯一参数是self

Examples you can confirm in a Python shell, tested with Python 3.5.3: 您可以在经过Python 3.5.3测试的Python Shell中确认示例:

x = "0.750"
x.lstrip("0")
> '.750'

# Included because a normal floating point type won't print trailing zeroes:
from decimal import Decimal
x = Decimal("0.750")
x.to_eng_string().lstrip("0")
> '.750'
str(x).lstrip("0")
> '.750'

While you won't be able to do this in Django templates unless you've swapped out the engine for jinja2 or something else that allows parens in method calls, you can either do this in the view (possibly ugly depending on how you're pulling this data) or in a simple custom template filter . 除非您已将引擎替换为jinja2或其他允许方法调用中进行括号的操作,否则您将无法在Django模板中执行此操作,但是您可以在视图中执行此操作(可能很难看,具体取决于您的操作方式提取此数据)或在简单的自定义模板过滤器中

I assume that value is greater than zero. 我假设该值大于零。

views.py views.py

def batting(request):
    battingregstd2018 = BattingRegStd.objects.filter(year=2018)

    for i in range(0, len(battingregstd2018)):
        # if need to edit value
        if battingregstd2018[i].obp is not None and battingregstd2018[i].obp < 1:
            # data edit as string
            # data type does not matter in template
            battingregstd2018[i].obp = str(battingregstd2018[i].obp)[1:]
        if battingregstd2018[i].ops is not None and battingregstd2018[i].ops < 1:
            battingregstd2018[i].ops = str(battingregstd2018[i].ops)[1:]

    return render(request, 'playerstats/battingReg2018.html', {'battingregstd2018':battingregstd2018})




than second attempt, 比第二次尝试
let's just fix template this time. 这次我们只修复模板。 use the original view.py 使用原始的view.py

{% for index in battingregstd2018%}
    <td>
    {% if index.obp is None %}
    -
    {% elif index.obp < 1 %}
    .{{index.obp|slugify|slice:"1:"}}
    {% else %}
    {{index.obp}}
    {% endif %}
    </td>
{% endfor %}

.{{index.obp|slugify|slice:"1:"}}
|slice can only be used in string data type. |slice只能在字符串数据类型中使用。
|slugify converts to ASCII for use |slice . |slugify转换为ASCII以便使用|slice but decimal point is deleted. 但小数点被删除。
so i added . 所以我加了. to the front. 到前面。

ps) PS)
maybe, float type will store 0.750 as 0.75 . 也许,浮点类型将存储0.7500.75 if you want to 0.750 than use it .{{index.obp|floatformat:"3"|slugify|slice:"1:"}} 如果您要使用它而不是0.750 .{{index.obp|floatformat:"3"|slugify|slice:"1:"}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM