【Django-02】 Model模型和模型描述对象Meta

Model和Meta

概念

就是对象的意思,底层一个Model对应一张表,而Meta是Model的内部类,是用来描述Model和数据库表的相关元数据信息,比如主键,排序,unique_key 的。

也不是啥新鲜的概念。

Model

所有自定义的模型都要继承django.db.models

Meta

Meta是你定义的模型的内部类,没啥稀奇的。

Model支持的字段类型

为了方便。Model到数据库都定义好了字段类型,这算是一种映射概念,也没啥稀奇的。

AutoField: 自增id

VooleanField: true/false 数据库存的是数字,模型映射为True/False

CharField: varchar类型

DateField:Date 日期【2023-10-01】

DateTimeField: 日期时间【2023-10-01 23:10:33】

IntergerField: int

TextField: 对应数据库text

TimeField:对应数据库Time [23:12:10]

FloatField: 对应数据库Double

FileField: 对应数据库varChar

ImageField:对应数据库varChar

DecumalField:对应数据库Decimal

Meta 属性

db_table: 值类型字符串->对应生成的数据库表名

manager:值类型 boolean ->是否还由Django管理生命周期

ordering: 值类型 列表->排序,字段前加'-' 表示降序

index_together:值类型列表中放元组,表示唯一键

unique_together:值类型列表中放元组,表示唯一键

例子

python 复制代码
class DwDatabaseAssetItemPwMap(models.Model):
    id = models.CharField(primary_key=True)
    asset_item_id = models.IntegerField('资产项id')
    asset_item_name = models.CharField('资产项名称', max_length=128, blank=True, null=True)
    name = models.CharField('服务器名', max_length=255)
    instance_id = models.CharField('实例id', max_length=128, blank=True, null=True)
    region = models.CharField('区域', max_length=255, blank=True, null=True)
    dw_server_id = models.IntegerField('dw服务器id')
    project = models.ForeignKey(Project, on_delete=models.CASCADE, verbose_name='项目')
    public_ip = models.CharField('公网ip', max_length=255, blank=True, null=True)
    local_ip = models.CharField('内网ip', max_length=255, blank=True, null=True)
    port = models.IntegerField('端口')
    asset_item_pw_id = models.IntegerField('密码id', null=True)
    username = models.CharField('账号', max_length=99)
    password = AesEncryptedCharField(verbose_name='密码', max_length=255)
    asset_id = models.IntegerField('资产项id', null=True)

    class Meta:
        app_label = 'test_table'
        managed = False
        db_table = 'dw_sink_database_asset_item_pw_map'
        unique_together = (('asset_item_id', 'dw_server_id', 'asset_item_pw_id',))
相关推荐
夜泉_ly2 小时前
MySQL -安装与初识
数据库·mysql
qq_529835353 小时前
对计算机中缓存的理解和使用Redis作为缓存
数据库·redis·缓存
月光水岸New5 小时前
Ubuntu 中建的mysql数据库使用Navicat for MySQL连接不上
数据库·mysql·ubuntu
狄加山6755 小时前
数据库基础1
数据库
我爱松子鱼5 小时前
mysql之规则优化器RBO
数据库·mysql
chengooooooo6 小时前
苍穹外卖day8 地址上传 用户下单 订单支付
java·服务器·数据库
Rverdoser7 小时前
【SQL】多表查询案例
数据库·sql
Galeoto7 小时前
how to export a table in sqlite, and import into another
数据库·sqlite
人间打气筒(Ada)7 小时前
MySQL主从架构
服务器·数据库·mysql
leegong231117 小时前
学习PostgreSQL专家认证
数据库·学习·postgresql