一、使用django连库建表
使用django连接数据库需要知道3个要点:
![](https://i-blog.csdnimg.cn/blog_migrate/e39b20d66da5d8efc0eb7ad23f79346b.png)
![](https://i-blog.csdnimg.cn/blog_migrate/9973271dd046fd1cdfdf3a453abaa1db.png)
![](https://i-blog.csdnimg.cn/blog_migrate/47d37f20705847008cb6ddcd7b155e50.png)
![](https://i-blog.csdnimg.cn/blog_migrate/39600faff72e29b444c3895b82a37dc1.png)
![](https://i-blog.csdnimg.cn/blog_migrate/f68837a3d2a3841a7071aa299fc276cf.png)
二、models 建表进阶
1
2
3
4
5
|
from
django.db
import
models
class
users(models.Model):
name
=
models.CharField(max_length
=
30
)
email
=
models.EmailField()
# EmailField 存储在数据库也是字符串,但是可以帮助前台做验证
memo
=
models.TextField()
|
那么我们有必要了解一下:怎样创建合适的表,怎样将类中的变量和表的字段对应起来?
True
注:当model中如果没有自增列,则自动会创建一个列名为id的列
1
2
3
4
5
6
7
|
class
Temp1(models.Model):
# 自动创建一个列名为id的且为自增的整数列
username
=
models.CharField(max_length
=
32
)
class
Temp2(models.Model):
# 自定义自增列
nid
=
models.AutoField(primary_key
=
True
)
name
=
models.CharField(max_length
=
32
)
|
![](https://i-blog.csdnimg.cn/blog_migrate/cd7e85d7b59648fbe9bd8094b12bdec6.png)
![](https://i-blog.csdnimg.cn/blog_migrate/1c07094e5f5f30983580e7f6318a79e9.png)
related_name:
![](https://i-blog.csdnimg.cn/blog_migrate/a53f4d0c6a4270e6a6b56fdc10eade63.png)
其实,machine和disk关联的都是device表的主键。
limit_choices_to :
如果我们有多个外键,但是外键所需要的数据并不相同,这时就用到了limit_choice_to。
这样,在我们设置的时候就会分别显示不同的数据:
附:
参数 | 描述 |
---|---|
edit_inline | 若取值非假, 这个关联对象就是可内联编辑的.这也意味着这个对象没有自己的管理界面.取值可以是 models.TABULAR 或 models.STACKED, 分别表示内联可编辑对象是显示成表格形式还是一个字段集栈的形式. |
limit_choices_to | 一个参数和值的字典(参阅`数据库API参考`_)用来限制 admin 针对该对象的可选项. 使用models.LazyDate 值来按日期限制该对象的选择项,举例来说: limit_choices_to = {'pub_date__lte' : models.LazyDate()} 只允许关联对象的pub_date在当前日期之前的才可以被选择. 本参数与 edit_inline 不相容. |
max_num_in_admin | 对内联编辑对象来说,这是在 amdin 中可显示的关联对象的最大值. 这样, 如果说一只比萨饼最多加10种浇头,那么 max_num_in_admin=10 将确保没有一个超过十种. 这并不说是比萨斜塔只有十层高...比萨斜塔是可以有更多层的.这个参数仅仅控制admin界面. |
min_num_in_admin | 在admin中显示的关联对象的最小值. 正常情况,在创建阶段显示 num_in_admin 个内联对象, 在编辑阶段,除了预先存在的关联对象外, 显示 num_extra_on_change 个空对象.不过, 无论何种情况,至少会有 min_num_in_admin 个关联对象被显示出来. |
num_extra_on_change | 在编辑阶段显示的额外的空白关联对象字段数. |
num_in_admin | 在添加一个对象时显示的其内联对象的默认数量 |
raw_id_admin | 为即将得到的整数值(id值)显示一个文本框而不是一个下拉菜单. 在关联对象有很多很多行时.使用它就比使用一个 <select> 更实用. 不能与 edit_inline 一起使用. |
related_name | 关系名字. 举例来说, 如果 Topping 对象拥有字段: models.ForeignKey(Pizza) related_name 将会是 "topping_set" (取自 类 的名字), Pizza 对象会自动拥有 topping_set对象集描述符. 不过若你在 Topping 类中做如下定义的话: models.ForeignKey(Pizza, related_name="munchie") 则 Topping 的对象集描述符就变为 munchie. 只有当一个对象要被另一个对象关联不止一次时, 这个参数才真正有用. 举例来说, 如果一个Story 对象既有 primary_category 字段又有 secondary_category 字段. 为了确保Category 对象拥有正确的对象集描述符,你要这样使用这些字段.: models.ForeignKey(Category, related_name="primary_storys") models.ForeignKey(Category, related_name="secondary_storys") ...这样 Category 对象才会自动拥有 primary_storys 和 secondary_storys 对象集描述符. |
to_field | 被关联对象的用于关联的字段. 默认情况, Django 使用被关联对象的主键 |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
|
SmallIntegerField(IntegerField):
-
小整数
-
32768
~
32767
PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField)
-
正小整数
0
~
32767
IntegerField(Field)
-
整数列(有符号的)
-
2147483648
~
2147483647
PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField)
-
正整数
0
~
2147483647
BigIntegerField(IntegerField):
-
长整型(有符号的)
-
9223372036854775808
~
9223372036854775807
自定义无符号整数字段
class
UnsignedIntegerField(models.IntegerField):
def
db_type(
self
, connection):
return
'integer UNSIGNED'
PS: 返回值为字段在数据库中的属性,Django字段默认的值为:
'AutoField'
:
'integer AUTO_INCREMENT'
,
'BigAutoField'
:
'bigint AUTO_INCREMENT'
,
'BinaryField'
:
'longblob'
,
'BooleanField'
:
'bool'
,
'CharField'
:
'varchar(%(max_length)s)'
,
'CommaSeparatedIntegerField'
:
'varchar(%(max_length)s)'
,
'DateField'
:
'date'
,
'DateTimeField'
:
'datetime'
,
'DecimalField'
:
'numeric(%(max_digits)s, %(decimal_places)s)'
,
'DurationField'
:
'bigint'
,
'FileField'
:
'varchar(%(max_length)s)'
,
'FilePathField'
:
'varchar(%(max_length)s)'
,
'FloatField'
:
'double precision'
,
'IntegerField'
:
'integer'
,
'BigIntegerField'
:
'bigint'
,
'IPAddressField'
:
'char(15)'
,
'GenericIPAddressField'
:
'char(39)'
,
'NullBooleanField'
:
'bool'
,
'OneToOneField'
:
'integer'
,
'PositiveIntegerField'
:
'integer UNSIGNED'
,
'PositiveSmallIntegerField'
:
'smallint UNSIGNED'
,
'SlugField'
:
'varchar(%(max_length)s)'
,
'SmallIntegerField'
:
'smallint'
,
'TextField'
:
'longtext'
,
'TimeField'
:
'time'
,
'UUIDField'
:
'char(32)'
,
BooleanField(Field)
-
布尔值类型
NullBooleanField(Field):
-
可以为空的布尔值
CharField(Field)
-
字符类型
-
必须提供max_length参数, max_length表示字符长度
TextField(Field)
-
文本类型
EmailField(CharField):
-
字符串类型,Django Admin以及ModelForm中提供验证机制
IPAddressField(Field)
-
字符串类型,Django Admin以及ModelForm中提供验证 IPV4 机制
GenericIPAddressField(Field)
-
字符串类型,Django Admin以及ModelForm中提供验证 Ipv4和Ipv6
-
参数:
protocol,用于指定Ipv4或Ipv6,
'both'
,
"ipv4"
,
"ipv6"
unpack_ipv4, 如果指定为
True
,则输入::ffff:
192.0
.
2.1
时候,可解析为
192.0
.
2.1
,开启刺功能,需要protocol
=
"both"
URLField(CharField)
-
字符串类型,Django Admin以及ModelForm中提供验证 URL
SlugField(CharField)
-
字符串类型,Django Admin以及ModelForm中提供验证支持 字母、数字、下划线、连接符(减号)
CommaSeparatedIntegerField(CharField)
-
字符串类型,格式必须为逗号分割的数字
UUIDField(Field)
-
字符串类型,Django Admin以及ModelForm中提供对UUID格式的验证
FilePathField(Field)
-
字符串,Django Admin以及ModelForm中提供读取文件夹下文件的功能
-
参数:
path, 文件夹路径
match
=
None
, 正则匹配
recursive
=
False
, 递归下面的文件夹
allow_files
=
True
, 允许文件
allow_folders
=
False
, 允许文件夹
FileField(Field)
-
字符串,路径保存在数据库,文件上传到指定目录
-
参数:
upload_to
=
"" 上传文件的保存路径
storage
=
None
存储组件,默认django.core.files.storage.FileSystemStorage
ImageField(FileField)
-
字符串,路径保存在数据库,文件上传到指定目录
-
参数:
upload_to
=
"" 上传文件的保存路径
storage
=
None
存储组件,默认django.core.files.storage.FileSystemStorage
width_field
=
None
, 上传图片的高度保存的数据库字段名(字符串)
height_field
=
None
上传图片的宽度保存的数据库字段名(字符串)
DateTimeField(DateField)
-
日期
+
时间格式 YYYY
-
MM
-
DD HH:MM[:ss[.uuuuuu]][TZ]
DateField(DateTimeCheckMixin, Field)
-
日期格式 YYYY
-
MM
-
DD
TimeField(DateTimeCheckMixin, Field)
-
时间格式 HH:MM[:ss[.uuuuuu]]
DurationField(Field)
-
长整数,时间间隔,数据库中按照bigint存储,ORM中获取的值为datetime.timedelta类型
FloatField(Field)
-
浮点型
DecimalField(Field)
-
10
进制小数
-
参数:
max_digits,小数总长度
decimal_places,小数位长度
BinaryField(Field)
-
二进制类型
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
null 数据库中字段是否可以为空
db_column 数据库中字段的列名
db_tablespace
default 数据库中字段的默认值
primary_key 数据库中字段是否为主键
db_index 数据库中字段是否可以建立索引
unique 数据库中字段是否可以建立唯一索引
unique_for_date 数据库中字段【日期】部分是否可以建立唯一索引
unique_for_month 数据库中字段【月】部分是否可以建立唯一索引
unique_for_year 数据库中字段【年】部分是否可以建立唯一索引
verbose_name Admin中显示的字段名称
blank Admin中是否允许用户输入为空
editable Admin中是否可以编辑
help_text Admin中该字段的提示信息
choices Admin中显示选择框的内容,用不变动的数据放在内存中从而避免跨表操作
如:gf
=
models.IntegerField(choices
=
[(
0
,
'何穗'
),(
1
,
'大表姐'
),],default
=
1
)
error_messages 自定义错误信息(字典类型),从而定制想要显示的错误信息;
字典健:null, blank, invalid, invalid_choice, unique,
and
unique_for_date
如:{
'null'
:
"不能为空."
,
'invalid'
:
'格式错误'
}
validators 自定义错误验证(列表类型),从而定制想要的验证规则
from
django.core.validators
import
RegexValidator
from
django.core.validators
import
EmailValidator,URLValidator,DecimalValidator,\
MaxLengthValidator,MinLengthValidator,MaxValueValidator,MinValueValidator
如:
test
=
models.CharField(
max_length
=
32
,
error_messages
=
{
'c1'
:
'优先错信息1'
,
'c2'
:
'优先错信息2'
,
'c3'
:
'优先错信息3'
,
},
validators
=
[
RegexValidator(regex
=
'root_\d+'
, message
=
'错误了'
, code
=
'c1'
),
RegexValidator(regex
=
'root_112233\d+'
, message
=
'又错误了'
, code
=
'c2'
),
EmailValidator(message
=
'又错误了'
, code
=
'c3'
), ]
)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
class
UserInfo(models.Model):
nid
=
models.AutoField(primary_key
=
True
)
username
=
models.CharField(max_length
=
32
)
class
Meta:
# 数据库中生成的表名称 默认 app名称 + 下划线 + 类名
db_table
=
"table_name"
# 联合索引
index_together
=
[
(
"pub_date"
,
"deadline"
),
]
# 联合唯一索引
unique_together
=
((
"driver"
,
"restaurant"
),)
# admin中显示的表名称
verbose_name
# verbose_name加s
verbose_name_plural
|