📜  BinaryField – Django 模型

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

BinaryField – Django 模型

BinaryField 是存储原始二进制数据的特殊字段。可以为它分配字节、字节数组或内存视图。默认情况下,BinaryField 将editable设置为False ,即它不能包含在 ModelForm 中。由于 BinaryField 存储原始数据或其他术语的Python对象,它不能手动输入,需要通过视图或 django shell 分配。这就是editable to False的意思,即不能通过任何形式进行编辑。

句法

field_name = models.BinaryField(**options)

Django 模型二进制字段说明

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

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

Python3
from django.db import models
from django.db.models import Model
# Create your models here.
 
class GeeksModel(Model):
    geeks_field = models.BinaryField()


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


Python3
# 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.BinaryField()),
            ],
        ),
    ]


Python3
# importing the model
# from geeks app
from geeks.models import GeeksModel
 
# creating a string
test_string = "GFG is best"
 
# creating a bytes object
res = bytes(test_string, 'utf-8')
 
# creating a instance of
# GeeksModel
geek_object = GeeksModel.objects.create(geeks_field = res)
geek_object.save()


将极客应用添加到 INSTALLED_APPS

Python3

# 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 的文件

Python3

# 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.BinaryField()),
            ],
        ),
    ]

因此,当您在项目上运行 makemigrations 时会创建一个 geeks_field BigIntegerField 。它是一个存储原始二进制数据的字段。

如何使用二进制字段?

任何类型的数据都可以转换为字节,包括整数、字符串、图像等。让我们尝试将字符串保存到 BinaryField 中。可以使用通用字节函数将字符串转换为字节。该函数在内部指向 CPython 库,该库隐式调用编码函数以将字符串转换为指定的编码。

Python3

# importing the model
# from geeks app
from geeks.models import GeeksModel
 
# creating a string
test_string = "GFG is best"
 
# creating a bytes object
res = bytes(test_string, 'utf-8')
 
# creating a instance of
# GeeksModel
geek_object = GeeksModel.objects.create(geeks_field = res)
geek_object.save()

现在让我们在管理服务器中检查它。我们创建了一个 GeeksModel 实例

binaryfield-django-models

可能的错误
如指定的那样,BinaryField 是不可编辑的字段,如果您手动尝试使用 editable=True 使其可编辑,则会产生意外错误。它应该在一个函数中创建,以便可以将对象分配给它。

binaryfield-editable-django-models

字段选项

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

下面是 BinaryField 可以使用的选项和属性。

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.