📜  DecimalField – Django 模型

📅  最后修改于: 2022-05-13 01:55:29.490000             🧑  作者: Mango

DecimalField – Django 模型

DecimalField 是一个存储固定精度十进制数的字段,在Python中由 Decimal 实例表示。它使用 DecimalValidator 验证输入。

句法

field_name = models.DecimalField(max_digits=None, decimal_places=None, **options)
DecimalField 具有以下必需参数 -
  • DecimalField.max_digits

    数字中允许的最大位数。请注意,此数字必须大于或等于 decimal_places。

  • DecimalField.decimal_places

    与数字一起存储的小数位数。

例如,要以 2 个小数位的分辨率存储最大 999 的数字,您可以使用:

models.DecimalField(..., max_digits=5, decimal_places=2)

并以小数点后 10 位的分辨率存储多达约 10 亿个数字:

models.DecimalField(..., max_digits=19, decimal_places=10)

Django 模型小数字段说明

使用示例说明 DecimalField。考虑一个名为geeks的项目,它有一个名为geeksforgeeks的应用程序。

极客应用的models.py文件中输入以下代码。

from django.db import models
from django.db.models import Model
# Create your models here.
  
class GeeksModel(Model):
    geeks_field = models.DecimalField(
                         max_digits = 5,
                         decimal_places = 2)

将极客应用添加到INSTALLED_APPS

# Application definition
  
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'geeks',
]

现在,当我们从终端运行makemigrations命令时,

Python manage.py makemigrations

将在geeks目录中创建一个名为 migrations 的新文件夹,其中包含一个名为0001_initial.py的文件

# Generated by Django 2.2.5 on 2019-09-25 06:00
  
from django.db import migrations, models
  
class Migration(migrations.Migration):
  
    initial = True
  
    dependencies = [
    ]
  
    operations = [
        migrations.CreateModel(
            name ='GeeksModel',
            fields =[
                ('id', 
                  models.AutoField(
                  auto_created = True,
                  primary_key = True,
                  serialize = False, 
                  verbose_name ='ID'
                )),
                ('geeks_field', models.DecimalField(
                                        max_digits = 5,
                                        decimal_places = 2
                )),
            ],
        ),
    ]

现在运行,

Python manage.py migrate

因此,当您在项目上运行迁移时,会创建一个geeks_field DecimalField 。它是一个存储datetime.date Python对象的字段。

如何使用小数域?

DecimalField 用于在数据库中存储Python datetime.date 实例。可以在数据库中存储任何类型的十进制数。让我们尝试在上面创建的模型中存储一个十进制数。

# importing the model
# from geeks app
from geeks.models import GeeksModel
  
# importing datetime module
import decimal
  
# creating an instance of 
# datetime.date
d = decimal.Decimal(9.53)
  
# creating an instance of 
# GeeksModel
geek_object = GeeksModel.objects.create(geeks_field = d)
geek_object.save()

现在让我们在管理服务器中检查它。我们已经创建了 GeeksModel 的一个实例。
DecimalField django 模型

字段选项

字段选项是赋予每个字段的参数,用于应用某些约束或将特定特征赋予特定字段。例如,向 DecimalField 添加参数null = True将使其能够在关系数据库中存储该表的空值。
以下是 DecimalField 可以使用的字段选项和属性。

Field OptionsDescription
NullIf True, Django will store empty values as NULL in the database. Default is False.
BlankIf True, the field is allowed to be blank. Default is False.
db_columnThe name of the database column to use for this field. If this isn’t given, Django will use the field’s name.
DefaultThe default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.
help_textExtra “help” text to be displayed with the form widget. It’s useful for documentation even if your field isn’t used on a form.
primary_keyIf True, this field is the primary key for the model.
editableIf False, the field will not be displayed in the admin or any other ModelForm. They are also skipped during model validation. Default is True.
error_messagesThe error_messages argument lets you override the default messages that the field will raise. Pass in a dictionary with keys matching the error messages you want to override.
help_textExtra “help” text to be displayed with the form widget. It’s useful for documentation even if your field isn’t used on a form.
verbose_nameA human-readable name for the field. If the verbose name isn’t given, Django will automatically create it using the field’s attribute name, converting underscores to spaces.
validatorsA list of validators to run for this field. See the validators documentation for more information.
UniqueIf True, this field must be unique throughout the table.