django之model多表操作

一对多表之间的查询:

class userInfo(models.Model):
    name = models.CharField(max_length=50)
    password = models.CharField(max_length=50)
    email = models.EmailField()
    user_type = models.ForeignKey('userType')
class userType(models.Model):
    name = models.CharField(max_length=50)

 

1.all,get,filter

·all:所有数据(序列)

·get:单挑数据,是一个对象(封装一行多列数据)

·filter:序列

  eg: 取id>5

    userInfo.objects.filter(id__gt = 5)

  eg:userType大于5的所有用户信息

    userInfo.objects.filter(user_type__id__gt=5 )

    说明:user_type就是userType对象

  eg:userType大名字包含a的所有用户信息

    userInfo.objects.filter(user_type__name__contains='a' )

 

    说明:user_type就是userType对象

  eg:查看用户类型等于超级管理员的所有用户

    userInfo.objects.filter(user_type__name = "超级管理员")==select * from userInfo xxx

    userInfo.objects.filter(user_type__name = "超级管理员").values('username') == select username from xxx

总结:对象__列名__方法 = ' '

多对多表之间查询:

 

class userInfo(models.Model):
    name = models.CharField(max_length=50)
    password = models.CharField(max_length=50)
    email = models.EmailField()
    user_type = models.ForeignKey('userType')

class userGroup(models.Model):
    group = models.CharField(max_length=50)
    user = models.ManyToManyField('userInfo')

 

1.建立关系

   t3 = userType.objects.get(name='supper')
    t4 = userType.objects.get(name='nomal')
    u1 = userInfo.objects.create(name='yj1',password='123',email='1@qq.com',user_type=t3) 
    u2 = userInfo.objects.create(name='yj1',password='123',email='1@qq.com',user_type=t4)
    groupObjA = userGroup.objects.create(group='HOSTA')
    groupObjA.user.add(u1) 
    groupObjB = userGroup.objects.create(group='HOSTB')
    groupObjB.user.add(u2)

分析: 两表多对多实质上就是用一个新表记录其关系, groupObjA.user.add(u1)可以理解为先执行groupObjA.user,即在表中插入groupObjA的id;再执行.add(u1),即插入u1的id

 2.两种建立方式

  1)groupObjA.user.add(u1)     == groupObjA有多对多字段

  2)   u1.userGroup_set.add(groupObjA) == u1无多对多字段

   

    

posted @ 2019-01-25 23:43  木叶小寒江  阅读(244)  评论(0编辑  收藏  举报