模型这块还差不少呢

master
roger 1 year ago
parent a4643fbd42
commit 2f83a3bd30
  1. 187
      orm_demo/orm_crud.py

@ -1,4 +1,6 @@
from orm_demo.models import *
from django.db.models import F, Q, Count
from django.db import connection
# 插入数据
# 先实例化对象,然后为对象赋值
@ -126,11 +128,196 @@ for user in skill_py.user.all():
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

Loading…
Cancel
Save