完成增删改的学习

master
roger_home_pc 1 year ago
parent 14b0860449
commit a4643fbd42
  1. 36
      orm_demo/orm_crud.py

@ -36,7 +36,7 @@ user_e1 = UserExtendInfo(username='张三', true_name='张三丰', sex=1, age=33
status=1, memo='', user=user1, depart=department1) status=1, memo='', user=user1, depart=department1)
user_e1.save() user_e1.save()
# 插入ManyToMany字段数据 # 插入ManyToMany字段数据add()和set()
skill_php = SkillInfo.objects.filter(skill_name='PHP').first() skill_php = SkillInfo.objects.filter(skill_name='PHP').first()
user_zhang = UserExtendInfo.objects.filter(username='张三').first() user_zhang = UserExtendInfo.objects.filter(username='张三').first()
skill_php.user.add(user_zhang) # 使用add方法添加外键关联关系 skill_php.user.add(user_zhang) # 使用add方法添加外键关联关系
@ -54,6 +54,15 @@ depart_zhou = DepartInfo.objects.filter(depart_name='设计部').first()
skill_draw.user.create(username='周七', true_name='周七天', sex=0, age=18, department='设计部', salary='8500.00', skill_draw.user.create(username='周七', true_name='周七天', sex=0, age=18, department='设计部', salary='8500.00',
status=1, memo='', user=user_zhou, depart=depart_zhou) 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() skill_dev = SkillInfo.objects.filter(skill_name__in=['JavaScript', 'PHP']).all()
user_dev = UserExtendInfo.objects.filter(department='开发部').all() user_dev = UserExtendInfo.objects.filter(department='开发部').all()
@ -100,3 +109,28 @@ for card in card_zhang:
# 反向查询 # 反向查询
card = CardInfo.objects.filter(user_id=1).first() card = CardInfo.objects.filter(user_id=1).first()
print(card.user.username) 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)
# 通过id指定删除哪个用户
skill_del = SkillInfo.objects.get(id=1)
result = skill_del.user.remove(2)
# 清除全部
skill_del = SkillInfo.objects.get(id=8)
result = skill_del.user.clear()

Loading…
Cancel
Save