-
单条INSERT
- (1).直接INSERT
# 返回model实例 Xxx.objects.create(xxx_type=Xxx.XxxTypeEnum.TYPE_TWO.val, xxx_name='test1')
- (2).先创建模型实例再赋值
obj = Xxx() obj.xxx_type = Xxx.XxxTypeEnum.TYPE_TWO.val obj.xxx_name = 'test1' # 不可省略 obj.save()
- 两种写法都可以,不做硬性规定
-
批量INSERT
- (1).多次INSERT
name_tuple = ('test2', 'test3', 'test4') for name in name_tuple: Xxx.objects.create(xxx_type=Xxx.XxxTypeEnum.TYPE_TWO.val, xxx_name=name)
- (2).bulk_create(objs:
Iterable
) ->List[Model]
name_tuple = ('test2', 'test3', 'test4') # bulk_create内部会对objs列表化处理,这里可以使用生成器 obj_gen = ( Xxx(xxx_type=Xxx.XxxTypeEnum.TYPE_TWO.val, xxx_name=name) for name in name_tuple) Xxx.objects.bulk_create(obj_gen) """实际执行SQL INSERT INTO `t_xxx` (`xxx_id`, `xxx_type`, `xxx_name`, `is_deleted`, `create_time`, `update_time`) VALUES ('c028b9798c333a08bd2dd15a8a00e755', 2, 'test2', 0, '2021-03-08 10:40:16.230221', '2021-03-08 10:40:16.230221'), ('0b5fdb4fd8303948b219025ca021a395', 2, 'test3', 0, '2021-03-08 10:40:16.230221', '2021-03-08 10:40:16.230221'), ('b226bd8bf72039138b2382bb3d7de34f', 2, 'test4', 0, '2021-03-08 10:40:16.230221', '2021-03-08 10:40:16.230221') """
- 通常情况推荐使用
bulk_create
,它使用了mysql的batch insert
仅传递一条SQL语句,减少网络交互次数 - 注意:如果行数非常多(如2000条以上),建议根据实际情况减少每次 bulk_create 的行数,分批提交,避免MySQL复制压力过大
-
单条UPDATE
- (1).直接UPDATE
- 注意:直接UPDATE,不会触发 auto_add,需要手动指定更新时间
import datetime xxx_id = 'babbc46ea7d13f03abaed27899f145e3' now = datetime.datetime.now() # 注意:直接UPDATE,不会触发 auto_add,需要手动指定更新时间 Xxx.objects.filter(xxx_id=xxx_id).update(update_time=now, xxx_name='test_update') """实际执行SQL UPDATE `t_xxx` SET `xxx_name` = 'test_update' , update_time = '2021-03-08 11:05:55.634693' WHERE `t_xxx`.`xxx_id` = 'babbc46ea7d13f03abaed27899f145e3' """
(2).获取模型对象后更新属性
xxx_id = 'babbc46ea7d13f03abaed27899f145e3' obj = Xxx.objects.get(xxx_id=xxx_id) obj.xxx_name = 'test_update' obj.save() """实际执行SQL SELECT `t_xxx`.`id`, `t_xxx`.`xxx_id`, `t_xxx`.`xxx_type`, `t_xxx`.`xxx_name`, `t_xxx`.`is_deleted`, `t_xxx`.`create_time`, `t_xxx`.`update_time` FROM `t_xxx` WHERE `t_xxx`.`xxx_id` = 'babbc46ea7d13f03abaed27899f145e3' UPDATE `t_xxx` SET `xxx_id` = 'babbc46ea7d13f03abaed27899f145e3', `xxx_type` = 2, `xxx_name` = 'test_update', `is_deleted` = 0, `create_time` = '2021-03-08 10:05:01.753900', `update_time` = '2021-03-08 11:05:55.634693' WHERE `t_xxx`.`id` = 1 """
- 推荐使用
法(1)
,禁止使用法(2)
- 法(1) 仅对指定字段进行更新,需要注意手动指定更新时间
- 法(2) 实际执行了两条SQL
- SELECT 部分为
SELECT * 全字段查询
,大部分为无关字段,增加I/O,降低性能;如果存在大字段,会极大降低mysql性能 - UPDATE 部分的
SET 为全字段更新
,增加mysql服务器CPU压力(mysql需要先判断值不同才更新),降低性能
- SELECT 部分为
- (1).直接UPDATE
-
多条UPDATE
-
直接UPDATE
字段__in
- 注意:直接UPDATE,不会触发 auto_add,需要手动指定更新时间
-
示例
import datetime xxx_id_tuple = ('x1', 'x2', 'x3') now = datetime.datetime.now() Xxx.objects.filter(xxx_id__in=xxx_id_tuple).update(update_time=now, xxx_name='test_update') """实际执行SQL UPDATE `t_xxx` SET `update_time` = '2021-03-08 11:31:31.339309' , `xxx_name` = 'test_update' WHERE `t_xxx`.`xxx_id` IN ('x1', 'x2', 'x3') """
-
- 禁止使用