Django中ORM操作

ORM操作:

class UserInfo(models.Model):

username = models.CharField(max_length=32)

password = models.CharField(max_length=64)

dp = models.ForeignKey(to='DePart',to_field='id')

# depart = models.ForeignKey('DePart')

class DePart(models.Model):

title = models.CharField(max_length=16)

# ForeignKey查询

# 正向跨表查询

# 1.对象

# q = models.UserInfo.objects.all()

# for row in q:

#      print(row.username,row.password,row.dp_id,row.dp.id,row.db.title)

# 2.字典

# q = models.UserInfo.objects.values('username','password','dp_id','dp__title')

# for row in q:

#      print(row['username'],row['dp__title'])

# 3.元祖

# q = models.UserInfo.objects.values_list('username','password','dp_id','dp__title')

# for row in q:

#      print(row[0],row[3])

# 反向跨表查询

# 1.对象

# v = models.DePart.objects.all()

# for row in v:

#      print(row.id,row.title,row.userinfo_set.all())

# 2.字典

# v = models.DePart.objects.values('id','title','userinfo__username','userinfo__password')

# for row in v:

#       print(row)

# 3.元祖

# v = models.DePart.objects.values('id','title','userinfo__username','userinfo__password')

# for row in v:

#      print(row)

# 自己写第三张表

def U2G(models.Model):

ui = models.ForeignKey('UserInfo')

ug = models.ForeignKey('UserGroup')

# 添加数据

models.U2G.objects.create(ui=1,ug=1)

models.U2G.objects.create(ui=1,ug=2)

models.U2G.objects.create(ui=2,ug=1)

models.U2G.objects.create(ui=2,ug=2)

# 查询

q = models.U2G.objects.all()

for row in q:

print(row.ui.username)

print(row.ug.caption)

# django 自动生成

m = models.ManyToManyField('UserInfo')

增加:

obj = models.UserGroup.objects.filter(id=2).first()

obj.m.add(1)

obj.m.add(1,2,3)

obj.m.add(*[1,2]) #一次多加一个

删除:

obj = models.UserGroup.objects.filter(id=2).first()

obj.m.remove(1)

obj.m.remove(2,3,4)

obj.m.remove(*[2,3,4])

清空:

obj.m.clear() # 没有参数

更新:设置为什么, 最后就只有什么

obj.m.set([3,])

查询:

q = obj.m.all()

print(q)

q = obj.m.filter()

上一篇:C#开发微信门户及应用(36)--微信卡劵管理的封装操作


下一篇:攻防世界PWN简单题 level2