📅  最后修改于: 2020-12-31 00:34:31             🧑  作者: Mango
在Django中,模型是用于包含基本字段和方法的类。每个模型类都映射到数据库中的单个表。
Django Model是django.db.models.Model的子类,模型类的每个字段都代表一个数据库字段(列)。
Django为我们提供了数据库抽象API,该API允许我们从映射表中创建,检索,更新和删除记录。
模型在Models.py文件中定义。该文件可以包含多个模型。
让我们看一个例子,我们正在创建一个模型Employee ,它具有两个字段first_name和last_name 。
from django.db import models
class Employee(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
first_name和last_name字段被指定为类属性,并且每个属性都映射到数据库列。
该模型将在数据库中创建一个表,如下所示。
CREATE TABLE appname_employee (
"id" INT NOT NULL PRIMARY KEY,
"first_name" varchar(30) NOT NULL,
"last_name" varchar(30) NOT NULL
);
创建的表包含一个自动创建的id字段。该表的名称是应用程序名称和型号名称的组合,可以进一步更改。
创建模型后,将模型注册到settings.py中的INSTALLED_APPS中。
例如,
INSTALLED_APPS = [
#...
'appname',
#...
]
在Model类内定义的字段是映射表的列名。字段名称不应该是Python保留字,例如clean,Save或Delete等。
Django提供了各种内置字段类型。
Field Name | Class | Particular |
---|---|---|
AutoField | class AutoField(**options) | It An IntegerField that automatically increments. |
BigAutoField | class BigAutoField(**options) | It is a 64-bit integer, much like an AutoField except that it is guaranteed to fit numbers from 1 to 9223372036854775807. |
BigIntegerField | class BigIntegerField(**options) | It is a 64-bit integer, much like an IntegerField except that it is guaranteed to fit numbers from -9223372036854775808 to 9223372036854775807. |
BinaryField | class BinaryField(**options) | A field to store raw binary data. |
BooleanField | class BooleanField(**options) | A true/false field. The default form widget for this field is a CheckboxInput. |
CharField | class DateField(auto_now=False, auto_now_add=False, **options) | It is a date, represented in Python by a datetime.date instance. |
DateTimeField | class DateTimeField(auto_now=False, auto_now_add=False, **options) | It is a date, represented in Python by a datetime.date instance. |
DateTimeField | class DateTimeField(auto_now=False, auto_now_add=False, **options) | It is used for date and time, represented in Python by a datetime.datetime instance. |
DecimalField | class DecimalField(max_digits=None, decimal_places=None, **options) | It is a fixed-precision decimal number, represented in Python by a Decimal instance. |
DurationField | class DurationField(**options) | A field for storing periods of time. |
EmailField | class EmailField(max_length=254, **options) | It is a CharField that checks that the value is a valid email address. |
FileField | class FileField(upload_to=None, max_length=100, **options) | It is a file-upload field. |
FloatField | class FloatField(**options) | It is a floating-point number represented in Python by a float instance. |
ImageField | class ImageField(upload_to=None, height_field=None, width_field=None, max_length=100, **options) | It inherits all attributes and methods from FileField, but also validates that the uploaded object is a valid image. |
IntegerField | class IntegerField(**options) | It is an integer field. Values from -2147483648 to 2147483647 are safe in all databases supported by Django. |
NullBooleanField | class NullBooleanField(**options) | Like a BooleanField, but allows NULL as one of the options. |
PositiveIntegerField | class PositiveIntegerField(**options) | Like an IntegerField, but must be either positive or zero (0). Values from 0 to 2147483647 are safe in all databases supported by Django. |
SmallIntegerField | class SmallIntegerField(**options) | It is like an IntegerField, but only allows values under a certain (database-dependent) point. |
TextField | class TextField(**options) | A large text field. The default form widget for this field is a Textarea. |
TimeField | class TimeField(auto_now=False, auto_now_add=False, **options) | A time, represented in Python by a datetime.time instance. |
first_name = models.CharField(max_length=50) # for creating varchar column
release_date = models.DateField() # for creating date column
num_stars = models.IntegerField() # for creating integer column
每个字段都需要一些用于设置列属性的参数。例如,CharField需要mac_length来指定varchar数据库。
适用于所有字段类型的通用参数。所有都是可选的。
Field Options | Particulars |
---|---|
Null | Django will store empty values as NULL in the database. |
Blank | It is used to allowed field to be blank. |
Choices | An iterable (e.g., a list or tuple) of 2-tuples to use as choices for this field. |
Default | The default value for the field. This can be a value or a callable object. |
help_text | Extra “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_key | This field is the primary key for the model. |
Unique | This field must be unique throughout the table. |
我们创建了一个Student模型,该模型在models.py文件中包含以下代码。
//models.py
class Student(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=30)
contact = models.IntegerField()
email = models.EmailField(max_length=50)
age = models.IntegerField()
之后,使用以下命令应用迁移。
python3 manage.py makemigrations myapp
它将创建一个表myapp_student 。该表的结构如下所示。