• Django--ORM 常用字段及属性介绍


    一、常用字段

    AutoField 字段

    int自增列,必须填入参数 primary_key=True。当model中如果没有自增列,则自动会创建一个列名为id的列。

    IntegerField 字段

    一个整数类型,范围在 -2147483648 to 2147483647。(一般不用它来存手机号(位数也不够),直接用字符串存,)

    CharField 字段

    字符类型,必须提供max_length参数, max_length表示字符长度。

    这里需要知道的是Django中的CharField对应的MySQL数据库中的varchar类型,没有设置对应char类型的字段,但是Django允许我们自定义新的字段,下面我来自定义对应于数据库的char类型

    from django.db import models
    
    #Django中没有对应的char类型字段,但是我们可以自己创建
    
    class FixCharField(models.Field):
        '''
        自定义的char类型的字段类
        '''
        def __init__(self,max_length,*args,**kwargs):
            self.max_length=max_length
            super().__init__(max_length=max_length,*args,**kwargs)
    
        def db_type(self, connection):
            '''
            限定生成的数据库表字段类型char,长度为max_length指定的值
            :param connection:
            :return:
            '''
            return 'char(%s)'%self.max_length
    
          
    #应用上面自定义的char类型
    class Test(models.Model):
        id=models.AutoField(primary_key=True)
        title=models.CharField(max_length=32)
        class_name=FixCharField(max_length=16)
        gender_choice=((1,'男'),(2,'女'),(3,'保密'))
        gender=models.SmallIntegerField(choices=gender_choice,default=3)
    
    • 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

     

    DateField 字段

    日期字段,日期格式 YYYY-MM-DD,相当于Python中的datetime.date( )实例

    DateTimeField 字段

    日期时间字段,格式 YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ],相当于Python中的datetime.datetime( )实例

    auto_now_add 参数

    配置auto_now_add=True,创建数据记录的时候会把当前时间添加到数据库。

    auto_now 参数

    配置上auto_now=True,每次更新数据记录的时候会更新该字段。


     

    BooleanField 字段

    给这个字段传 bool 值会自动转换成 0 或1,一般用在状态二选一

    TextField 字段

    用于存储大段文本,且不需要指定字段参数,内容没有大小限制

    EmailField 字段

    字符串类型,存储邮箱格式数据

    FileField 字段

    字符串,路径保存在数据库,文件上传到指定目录

    参数:
    upload_to = "" 上传文件的保存路径
    storage = None 存储组件,默认django.core.files.storage.FileSystemStorage

    ImageField 字段

    字符串,路径保存在数据库,文件上传到指定目录

    参数:
    upload_to = "" 上传文件的保存路径
    storage = None 存储组件,默认django.core.files.storage.FileSystemStorage
    width_field=None 上传图片的高度保存的数据库字段名(字符串)
    height_field=None 上传图片的宽度保存的数据库字段名(字符串)


     

    二、字段参数

    null

    用于表示某个字段可以为空。

    unique

    如果设置为unique=True 则该字段在此表中必须是唯一的 。

    db_index

    如果db_index=True 则代表着为此字段设置索引。

    default

    为该字段设置默认值


     

    choice 参数

    针对某个字段有可以列举完全的情况,我们一般都是使用choice参数

    class Server(models.Model):
        host = models.CharField(max_length=32)
        status_choice = (
            (1,'在线'),
            (2,'不在线'),
        )
        status = models.IntegerField(choices=status_choice)
    
        desc_choice=(
            ('hh',6666666),
            ('zz',0000000),
        )
        desc = models.CharField(max_length=32,choices=desc_choice)
        
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    新建数据之后,在数据库中存储的字段就是 statusdesc而不是各自对应的值

    Server.objects.create(host='127.0.0.1',status=1,desc='不在选择表中')
    Server.objects.create(host='127.0.0.2',status=2,desc='hh')
    
    • 1
    • 2
    res = Server.objects.filter(pk=1).first()
    print(res.status)
    # 结果为 1
    
    • 1
    • 2
    • 3

    想要查看各自对应的值需要借助get_字段名_display()

    res = Server.objects.filter(pk=1).first()
    print(res.status)
    print(res.get_status_display())
    
    print(res.desc)
    print(res.get_desc_display())
    # 1
    # 在线
    # 不在选择表中
    # 不在选择表中
    
    
    res = Server.objects.filter(pk=2).first()
    print(res.status)
    print(res.get_status_display())
    
    print(res.desc)
    print(res.get_desc_display())
    # 2
    # 不在线
    # hh
    # 6666666
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    三、外键字段

    3.1 ForeignKey 字段

    外键类型在ORM中用来表示外键关联关系,一般把ForeignKey字段设置在 '一对多’中’多’的一方。

    ForeignKey可以和其他表做关联关系同时也可以和自身做关联关系。

    ForeignKey 字段参数

    to

    设置要关联的表

    to_field

    设置要关联的表的字段,不写默认为主键

    on_delete

    当删除关联表中的数据时,当前表与其关联的行的行为。

    models.DO_NOTHING
    删除关联数据,引发错误IntegrityError,去掉外键关系
    
    
    models.PROTECT
    删除关联数据,引发错误ProtectedError
    
    
    models.SET_NULL
    删除关联数据,与之关联的值设置为null(前提FK字段需要设置为可空)
    
    
    models.SET_DEFAULT
    删除关联数据,与之关联的值设置为默认值(前提FK字段需要设置默认值)
    
    models.CASCADE
    删除关联数据,与之关联的值也删除
    
    models.SET(值或者函数名)
    
    删除关联数据,
    a. 与之关联的值设置为指定值,设置:models.SET()
    b. 与之关联的值设置为可执行对象的返回值,设置:models.SET(可执行对象)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    例如:

    def func():
        return 10
    
    class MyModel(models.Model):
        user = models.ForeignKey(
            to="User",
            to_field="id",
            on_delete=models.SET(func)
        )
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    db_constraint

    是否在数据库中创建外键约束,默认为True。


     

    3.2 OneToOneField 字段

    一对一字段。

    通常一对一字段用来扩展已有字段。(通俗的说就是一个人的所有信息不是放在一张表里面的,简单的信息一张表,隐私的信息另一张表,之间通过一对一外键关联)

    OneToOneField 字段参数

    to–设置要关联的表。

    to_field–设置要关联的字段。

    on_delete–当删除关联表中的数据时,当前表与其关联的行的行为。(参考上面的例子)


     

    3.3 ManyToManyField 字段

    多对多字段

    区别于原生 SQL 创建多对多需要手动创建一张关系表,ORMManyToManyField自动创建第三张关系表,并且创建出的字段是虚拟字段,不会在表中展示出来

    ManyToManyField 字段参数

    to–设置要关联的表。

    to_field–设置要关联的字段。

    on_delete–当删除关联表中的数据时,当前表与其关联的行的行为。(参考上面的例子)


     

    四、字段合集

    		AutoField(Field)
            - int自增列,必须填入参数 primary_key=True
    
        BigAutoField(AutoField)
            - bigint自增列,必须填入参数 primary_key=True
    
            注:当model中如果没有自增列,则自动会创建一个列名为id的列
            from django.db import models
    
            class UserInfo(models.Model):
                # 自动创建一个列名为id的且为自增的整数列
                username = models.CharField(max_length=32)
    
            class Group(models.Model):
                # 自定义自增列
                nid = models.AutoField(primary_key=True)
                name = models.CharField(max_length=32)
    
        SmallIntegerField(IntegerField):
            - 小整数 -3276832767
    
        PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField)
            - 正小整数 032767
        IntegerField(Field)
            - 整数列(有符号的) -21474836482147483647
    
        PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField)
            - 正整数 02147483647
    
        BigIntegerField(IntegerField):
            - 长整型(有符号的) -92233720368547758089223372036854775807
    
        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
    • 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
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115

     

    五、ORM 与 MySQL 对应关系

    对应关系:
        '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)',
    
    • 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
  • 相关阅读:
    【Windows下搭建深度学习环境之TensorFlow篇】一气呵成,五步搞定TensorFlow的安装!TensorFlow的安装之路
    Python中RotatingFileHandler、TimedRotatingFileHandler函数用法
    抖音手机实景无人直播间怎么搭建?
    A Guide to Java HashMap
    ImageView的八种ScaleType
    元宇宙还是香啊
    idea java新建项目详细步骤
    RocketMQ集群监控平台rocketmq-console
    Tomcat项目启动报错
    常用邮件服务器支持端口及加密方法实测
  • 原文地址:https://blog.csdn.net/weixin_43988680/article/details/125450088