随笔 - 105  文章 - 0  评论 - 0  阅读 - 40744

Django中的Model字段

字段选项

这里的选项,适用于所有的字段类型,且都是可选的
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
null # 如果设置为 True, 当该字段为空时,Django 会将数据库中该字段设置为 NULL,默认为 False
blank # 如果设置为 True ,该字段允许为空。默认为 False 。
choices # 用于提供选项,如果设置了此参数,则在ModelForm的widget不是使用了text输入框,而是select标签
# choices的例子
gender_choices = ((1, '男'), (2, '女'))
gender = models.SmallIntegerField(verbose_name='性别', choices=gender_choices)
# choices结束
# 使用选项的另一种方式
class Card(models.Model):
 
    class Suit(models.IntegerChoices):
        DIAMOND = 1
        SPADE = 2
        HEART = 3
        CLUB = 4
 
    suit = models.IntegerField(choices=Suit.choices)
db_column  # 在数据库中生成的字段名
db_index  # 如果设为True,则此字段为索引
db_tablespace  # 不清楚
default  # 该字段的默认值。可以是一个值或者是个可调用的对象,如果是个可调用对象,每次实例化模型时都会调用该对象。
editable  # 默认为True,如果为False,则在admin或ModelForm中不显示,同时也会跳过验证
error_messages  # 自定义错误信息
help_text # 额外的“帮助”文本,随表单控件一同显示。即便你的字段未用于表单,它对于生成文档也是很有用的。
primary_key  # True则表明是主键
unique  # 如果设置为 True,这个字段必须在整个表中保持值唯一。
unique_for_date  # 此字段要与设置的DateField或者DateTimeField字段联合唯一,如下:
title = models.CharField(max_length=32, unique_for_date='pub_date')
pub_date = models.DateField()
unique_for_month  # 类似以上
unique_for_year  # 类似以上
verbose_name  # 方便阅读的名称
validators  # 自定义验证规则,可参考https://docs.djangoproject.com/en/3.0/ref/validators/

字段中的特殊选项

不同类型的字段也有其特殊的选项,不适合于其它字段的

BinaryField

二进制类型字段 BinaryField.max_length

CharField

字符串型字段 CharField.max_length

DateField、TimeField

DateField.auto_now:每次调用obj.save时更新修改时间,用QuerySet方法没效 DateField.auto_now_add:保存创建时间

DecimalField

带有小数的数值 DecimalField.max_digits:最大的位数 DecimalField.decimal_places:小数点位数

FileField

FileField.upload_to
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 例一
class MyModel(models.Model):
    # file will be uploaded to MEDIA_ROOT/uploads
    upload = models.FileField(upload_to='uploads/')
    # or...
    # file will be saved to MEDIA_ROOT/uploads/2015/01/30
    upload = models.FileField(upload_to='uploads/%Y/%m/%d/')
# 例二
def user_directory_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
    return 'user_{0}/{1}'.format(instance.user.id, filename)
 
class MyModel(models.Model):
    upload = models.FileField(upload_to=user_directory_path)
</filename></id>

如何使用FileField字段,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from django.db import models
 
class Car(models.Model):
    name = models.CharField(max_length=255)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    photo = models.ImageField(upload_to='cars')
from django.core.files import File
 
# Create a Python file object using open()
f = open('/path/to/hello.world', 'w')
myfile = File(f)
car1.photo = myfile
myfile.close()
# 文件相关操作
car1.photo.name
car1.photo.size
car1.photo.url
car1.photo.path
car1.photo.open(mode='rb')
car1.photo.close()
car1.photo.save(name, content, save=True)
car1.photo.delete(save=True)

FilePathField

这其实是一个带有choices属性的CharField,有以下参数 path:必选,是一个路径,可调用一个方法生成 match:正则表达式,匹配的是文件名,不匹配路径 recursive:包括路径中的子目录 allow_files:允许文件 allow_folders:允许目录

ImageField

有FileField的所有属性,依赖于pillow,参数如下: height_field,width_field:保存高度、宽度的字符串名称

GenericIPAddressField

参数: protol:both、IPV4、IPV6 unpack_ipv4:IPV4 IPV6映射,需要protocal为both

UUIDField

可代替AutoField(primary_key=True)
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
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
 
 
 
 
 
<h2>ForeignKey<button class="cnblogs-toc-button" title="显示目录导航" aria-expanded="false"></button></h2>
多对一的外键约束,有以下参数:
to:关联表(必须)
on_delete:关联数据被删除行为 (必须),有以下,都在模块django.db.models下
    CASCADE:同时删除
    PROTECT:保护数据
    SET_NULL:关联数据设为空,注意要配置null=True使用
    SET_DEFAULT:设默认值
    SET():设为指定的值,参数可为一个可调用的函数
    DO_NOTHING:什么都不做
limit_choices_to:用于ModelForm或者admin,用于限制选择的条件,可为Q对象或{字段:值}或一个可调用函数
related_name:反查,一般先获取obj,然后obj.定义的related_name.all()
related_query_name:也是反查,一般用于filter
 
 
 
 
<pre class="brush:python"># models
class Book(models.Model):
    title = models.CharField(max_length=32)
    author = models.ForeignKey(to='Author', on_delete=models.CASCADE, related_name='author_field',
                               related_query_name='author_tab')
 
 
class Author(models.Model):
    name = models.CharField(max_length=32)
# views
# 查询 pk=1出版的书
    author = models.Author.objects.get(pk=1)
    print(author.author_field.all())
    # 查询出版python基础的作者
    print(models.Author.objects.filter(author_tab__title='Python基础'))
    return HttpResponse('...')
</pre>
<p>to_field:关联的字段,需要设此字段为unique=True<br>
db_constrains:设为False则不外键约束,但一般不会这样做<br>
swappable:一般不会改</p>
<h2>ManyToManyField<button class="cnblogs-toc-button" title="显示目录导航" aria-expanded="false"></button></h2>
ForeignKey中的参数都具有,还有以下参数
through:第三张表类的名称
through_fields:关联的字段
<pre class="brush:python">from django.db import models
 
class Person(models.Model):
    name = models.CharField(max_length=50)
 
class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(
        Person,
        through='Membership',
        through_fields=('group', 'person'),
    )
 
class Membership(models.Model):
    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    person = models.ForeignKey(Person, on_delete=models.CASCADE)
    inviter = models.ForeignKey(
        Person,
        on_delete=models.CASCADE,
        related_name="membership_invites",
    )
    invite_reason = models.CharField(max_length=64)
</pre>
<p>db_table:在数据库中创建的第三张表名称<br>
symmetrical:默认为True,一般用在关联的是自己表格的时候</p>
<h2>OneToOneField<button class="cnblogs-toc-button" title="显示目录导航" aria-expanded="false"></button></h2>
参数:
parent_link:沿不明白
<h2>其它字段<button class="cnblogs-toc-button" title="显示目录导航" aria-expanded="false"></button></h2>
AutoField BigAutoField BigIntegerField BooleanField DurationField EmailField IntegerField NullBooleanField PositiveIntegerField PostiveSmallField
SlugField:只有字母、数字、下划线、连接符,一般用于URL,参数:allow_unicode
SmallAutoField SmallIntegerField Textfield
posted on   Treelight  阅读(531)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· AI 智能体引爆开源社区「GitHub 热点速览」
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

点击右上角即可分享
微信分享提示