You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
323 lines
9.7 KiB
323 lines
9.7 KiB
from orm_demo.models import * |
|
from django.db.models import F, Q, Count |
|
from django.db import connection |
|
|
|
# 插入数据 |
|
# 先实例化对象,然后为对象赋值 |
|
depart_data = DepartInfo() |
|
depart_data.depart_name = '开发部' |
|
depart_data.save() |
|
|
|
# 实例化对象同时赋值 |
|
skill_data = SkillInfo(skill_name='PHP') |
|
skill_data.save() |
|
|
|
# create方法赋值 |
|
user = BaseUserInfo.objects.create(username='张三', password='zhangsan', status=1) |
|
|
|
# create方式赋值, 字典格式数据 |
|
data = {'username': '李四', 'password': 'lisi', 'status': 1} |
|
# data2 = dict(username='李四', password='lisi', status=1) # 另一种字典数据定义形势 |
|
user2 = BaseUserInfo.objects.create(**data) |
|
|
|
# 批量插入 |
|
data_list = [ |
|
{'username': '王五', 'password': 'wangwu', 'status': 1}, |
|
{'username': '孙六', 'password': 'sunliu', 'status': 1} |
|
] |
|
user_obj_list = [] |
|
for data in data_list: |
|
user_obj = BaseUserInfo(username=data['username'], password=data['password'], status=data['status']) |
|
user_obj_list.append(user_obj) |
|
users = BaseUserInfo.objects.bulk_create(user_obj_list) |
|
|
|
# 插入外键关联的数据 |
|
user1 = BaseUserInfo.objects.filter(username='张三').first() |
|
department1 = DepartInfo.objects.filter(depart_name='开发部').first() |
|
user_e1 = UserExtendInfo(username='张三', true_name='张三丰', sex=1, age=33, department='开发部', salary='230000.00', |
|
status=1, memo='', user=user1, depart=department1) |
|
user_e1.save() |
|
|
|
# 插入ManyToMany字段数据add()和set() |
|
skill_php = SkillInfo.objects.filter(skill_name='PHP').first() |
|
user_zhang = UserExtendInfo.objects.filter(username='张三').first() |
|
skill_php.user.add(user_zhang) # 使用add方法添加外键关联关系 |
|
|
|
# 一次建立多个连接关系 |
|
skill_py = SkillInfo.objects.filter(skill_name='Python').first() |
|
user_zhang = UserExtendInfo.objects.filter(username='张三').first() |
|
user_sun = UserExtendInfo.objects.filter(username='孙六').first() |
|
skill_py.user.add(user_zhang, user_sun) # add方法可以添加多个关联关系 |
|
|
|
# 直接创建关联关系数据 |
|
skill_draw = SkillInfo.objects.filter(skill_name='draw').first() |
|
user_zhou = BaseUserInfo.objects.filter(username='周七').first() |
|
depart_zhou = DepartInfo.objects.filter(depart_name='设计部').first() |
|
skill_draw.user.create(username='周七', true_name='周七天', sex=0, age=18, department='设计部', salary='8500.00', |
|
status=1, memo='', user=user_zhou, depart=depart_zhou) |
|
|
|
# 使用set修改关联数据 |
|
user_design = UserExtendInfo.objects.filter(department='设计部').all() |
|
skill_ps = SkillInfo.objects.get(skill_name='Photoshop') |
|
skill_ps.user.set(user_design) |
|
|
|
# 直接给定id |
|
skill_draw = SkillInfo.objects.get(skill_name='draw') |
|
skill_draw.user.set([3]) |
|
|
|
# 批量关联多对多数据 |
|
skill_dev = SkillInfo.objects.filter(skill_name__in=['JavaScript', 'PHP']).all() |
|
user_dev = UserExtendInfo.objects.filter(department='开发部').all() |
|
for skill in skill_dev: |
|
skill.user.add(*user_dev) |
|
|
|
# 更新数据 |
|
# 查询出结果后通过赋值方式使用save方法保存 |
|
skill_data = SkillInfo.objects.filter(skill_name='测试').first() |
|
skill_data.skill_name = 'Test' |
|
skill_data.save() |
|
|
|
# 使用update方式直接修改 |
|
skill_data1 = SkillInfo.objects.filter(skill_name='画图').update(skill_name='draw') |
|
|
|
# 删除数据 返回删除结果 (2, {'orm_demo.SkillInfo': 2}) |
|
SkillInfo.objects.create(skill_name='delete') |
|
SkillInfo.objects.create(skill_name='delete') |
|
del_skill = SkillInfo.objects.filter(skill_name='delete').delete() |
|
print(del_skill) |
|
|
|
# 关联表查询 一对一 |
|
# 通过扩展表名查询 |
|
user_li = BaseUserInfo.objects.filter(username='李四').first() |
|
print(user_li.userextendinfo.true_name) # 扩展表名需要小写, 返回:李四喜 |
|
|
|
# 通过关联字段查询 |
|
user_extend_li = UserExtendInfo.objects.filter(true_name__contains='李四').first() |
|
print(user_extend_li.user.password) # 使用关联字段名称, 返回:lisi |
|
|
|
# 关联表查询 一对多 |
|
# 正向查询 |
|
user_zhang = BaseUserInfo.objects.get(id=1) |
|
card_zhang = user_zhang.cardinfo_set.all() # 使用小写的表名加上_set做为关联字段 |
|
for card in card_zhang: |
|
print(card.card_no) |
|
|
|
# 正向查询 related_name 指定关联名称 |
|
user_zhang = BaseUserInfo.objects.get(id=1) |
|
card_zhang = user_zhang.user_card.all() # 使用指定的关联名做为关联字段 |
|
for card in card_zhang: |
|
print(card.card_no) |
|
|
|
# 反向查询 |
|
card = CardInfo.objects.filter(user_id=1).first() |
|
print(card.user.username) |
|
|
|
# 多对多查询 |
|
# 正向查询 |
|
user_zhang = UserExtendInfo.objects.get(username='张三') |
|
skill_user_zhang = user_zhang.skillinfo_set.all() |
|
print(skill_user_zhang) |
|
|
|
# 反向查询 |
|
skill_py = SkillInfo.objects.filter(skill_name='Python').first() |
|
for user in skill_py.user.all(): |
|
print(user.true_name) |
|
|
|
# 多对多删除关联数据 remove clear |
|
# 删除指定用户的指定技能 |
|
user_del = UserExtendInfo.objects.get(id=5) |
|
skill_del = SkillInfo.objects.get(id=7) |
|
result = skill_del.user.remove(user_del) |
|
print(result) |
|
|
|
# 通过id指定删除哪个用户 |
|
skill_del = SkillInfo.objects.get(id=1) |
|
result = skill_del.user.remove(2) |
|
print(result) |
|
|
|
# 清除全部 |
|
skill_del = SkillInfo.objects.get(id=8) |
|
result = skill_del.user.clear() |
|
print(result) |
|
|
|
# ForeignKey 直接获取关联表数据, 只能用在一对多设置外键的情况 |
|
card_data = CardInfo.objects.select_related('user') |
|
for card in card_data: |
|
print(card.user) |
|
|
|
# ManyToMany 多对多直接获取关联表数据 |
|
skill_data = SkillInfo.objects.prefetch_related('user') |
|
for skill in skill_data: |
|
print(skill.skill_name) |
|
users = skill.user.all() |
|
for user in users: |
|
print(user.true_name) |
|
|
|
# F()函数 |
|
users = UserExtendInfo.objects.all() |
|
for user in users: |
|
user.salary = F('salary') + 1000 |
|
user.save() |
|
for user in users: |
|
user.refresh_from_db() |
|
print(user.salary) |
|
|
|
# Q()函数 用于多条件查询 |
|
user = UserExtendInfo.objects.filter(Q(age__gt=30) & Q(salary__gt=10000)).first() |
|
print(user.username) |
|
|
|
# 执行原生SQL |
|
users = UserExtendInfo.objects.raw("SELECT * FROM orm_user_base_info") |
|
for user in users: |
|
print(type(user), user.username) |
|
|
|
sql = "SELECT * FROM orm_user_extend_info WHERE age > %s and salary > %s" |
|
users = UserExtendInfo.objects.raw(sql, [30, 10000]) |
|
for user in users: |
|
print(type(user), user.username) |
|
|
|
# connect 游标 |
|
# 插入数据 |
|
import django.utils.timezone as timezone |
|
|
|
time_now = timezone.now() |
|
cursor = connection.cursor() |
|
sql = "INSERT INTO orm_skill_info (skill_name, createDate) VALUES (%s, %s)" |
|
cursor.execute(sql, ('selenium', time_now)) |
|
cursor.close() |
|
|
|
# 查询数据 |
|
sql = "SELECT * FROM orm_user_extend_info" |
|
cursor = connection.cursor() |
|
cursor.execute(sql) |
|
row = cursor.fetchone() |
|
print(row) |
|
cursor.close() |
|
|
|
# 更新数据 |
|
cursor = connection.cursor() |
|
try: |
|
update_sql = "UPDATE orm_depart_info SET depart_name = %s WHERE id = %s" |
|
data = ('开发部', 1) |
|
cursor.execute(update_sql, data) |
|
rowcount = cursor.rowcount |
|
print(rowcount) |
|
connection.commit() |
|
except Exception as e: |
|
print(e) |
|
connection.rollback() |
|
finally: |
|
cursor.close() |
|
|
|
# 事务处理 transaction |
|
from django.db import transaction |
|
|
|
|
|
# 方式1:修饰器 |
|
|
|
@transaction.atomic |
|
def trans(request): |
|
save_id = transaction.savepoint() # 开启事件 |
|
try: |
|
# somecode |
|
transaction.savepoint_commit(save_id) # 提交事件 |
|
except Exception as e: |
|
print(e) |
|
transaction.savepoint_rollback(save_id) # 回滚事件 |
|
|
|
|
|
# 方式2: with语句 |
|
|
|
def trans_with(request): |
|
with transaction.atomic(): |
|
save_id = transaction.savepoint() # 开启事件 |
|
try: |
|
# some code |
|
transaction.commit(save_id) # 提交事件 |
|
except Exception as e: |
|
print(e) |
|
transaction.rollback(save_id) # 回滚事件 |
|
|
|
|
|
# 基本查询 |
|
# get 当查询结果多余一条时报错 |
|
user = BaseUserInfo.objects.get(id=2) |
|
print(user) |
|
|
|
# exclude 排除查询出来的数据 |
|
users = UserExtendInfo.objects.exclude(age__lt=30) |
|
for user in users: |
|
print(user.true_name) |
|
|
|
# filter 过滤数据 |
|
users = UserExtendInfo.objects.filter(Q(age__gte=30) & Q(department__in=['开发部', '测试部'])) |
|
for user in users: |
|
print(user.true_name) |
|
|
|
# __gt __gte __lt __lte __in __contains __year __month __day |
|
users = BaseUserInfo.objects.filter(username__contains="孙") |
|
for user in users: |
|
print(user) |
|
|
|
users = BaseUserInfo.objects.filter(create_date__year='2023') |
|
for user in users: |
|
print(user.create_date) |
|
|
|
users = BaseUserInfo.objects.filter(create_date__day='08') |
|
for user in users: |
|
print(user.create_date) |
|
|
|
# values 用于指定显示具体字段 |
|
users = UserExtendInfo.objects.filter(username='张三').values('username', 'true_name', 'salary') |
|
for user in users: |
|
print(user) |
|
print(user['true_name']) |
|
|
|
# distinct 去重 |
|
departs = UserExtendInfo.objects.distinct().values('department') |
|
for d in departs: |
|
print(d) |
|
|
|
# 链式过滤器 |
|
users = UserExtendInfo.objects.filter(age__range=[20, 30]).exclude(salary__lt=17000) |
|
for user in users: |
|
print(user.username) |
|
|
|
# 结果切片 |
|
skills = SkillInfo.objects.all()[1:3] |
|
print(skills) |
|
|
|
# 排序 order_by |
|
user_salary = UserExtendInfo.objects.order_by('salary').all() |
|
for user in user_salary: |
|
print(user.salary) |
|
|
|
# 排序 desc |
|
user_salary = UserExtendInfo.objects.order_by(F('salary').desc()) |
|
for user in user_salary: |
|
print(user.salary) |
|
|
|
# 排序 asc |
|
user_salary = UserExtendInfo.objects.order_by(F('salary').asc()) |
|
for user in user_salary: |
|
print(user.salary) |
|
|
|
# group_by query形式 |
|
users = UserExtendInfo.objects.all() |
|
users.query.group_by = ['department'] |
|
for user in users: |
|
print(user.username, user.department) |
|
|
|
# group_by aggregated count |
|
users = UserExtendInfo.objects.values('username').aaggregate(count=Count('department')) |
|
print(users) |
|
|
|
# count |
|
|
|
|
|
# sum |
|
|
|
# UNION |
|
|
|
|
|
# JOIN
|
|
|