Django Models一对多操作

特别注意:

新版django新建ForeignKey时需要添加 on_delete=models.CASCADE,即

models.ForeignKey("UserType",on_delete=models.CASCADE)


一,新建models文件
class UserInfo(models.Model):
name = models.CharField(max_length=10)
password = models.CharField(max_length=100)
user_type = models.ForeignKey("UserType",on_delete=models.CASCADE)


class UserType(models.Model):
id = models.AutoField(primary_key=True)
caption = models.CharField(max_length=10)


二,在views下添加数据
1.使用create添加数据
models.UserType.objects.create(caption="管理员")

2.使用对象管理添加数据
  2.1
    obj = models.UserType()
    obj.caption = "超级管理员"
    obj.save()
  2.2
    obj1 = models.UserType(caption="普通用户")
    obj1.save()

3.使用字典方式添加数据
  user_type_dict = {"caption":"打杂的"}
  models.UserType.objects.create(**user_type_dict)

  user_info_dict1 = {"name":"n1","password":"123","user_type":models.UserType.objects.get(caption="管理员")}
  models.UserInfo.objects.create(**user_info_dict1)

  user_info_dict2 = {"name": "n2", "password": "123", "user_type": models.UserType.objects.get(caption="超级管理员")}
  models.UserInfo.objects.create(**user_info_dict2)

  user_info_dict3 = {"name": "n3", "password": "123", "user_type": models.UserType.objects.get(caption="普通用户")}
  models.UserInfo.objects.create(**user_info_dict3)

三,models正向查找

  1.通过外键查找其他表数据
      obj = models.UserInfo.objects.filter(name="n1").first()
      print(obj.user_type.caption)
      通过UserInfo表查找UserType表的caption列的数据,使用外键user_type

  2.通过牛逼的双下划线__正向连表操作
      obj = models.UserInfo.objects.filter(name="n1",user_type__caption="管理员").values("name","user_type__caption")
      print(obj.all().first().get("name"))
      通过filter过滤条件,通过外键__其他表的属性来操作其他表,这与第一种操作方式(三【1】)的区别是:
      这是对 对象来进行操作,而之前都是通过对某一行具体的数据进行操作
      values方法表示新数据有哪些列,values会生成一个字典,还有一个values_list,会生成一个元组

四,models反向查找

  1.通过_set反向查找
      obj = models.UserType.objects.filter(caption="管理员").first()
      print(obj.userinfo_set.all().first().password)
      反向查找时时通过其他表的表名加_set进行列的选取,而正向查找时时通过外键,除此之外,userinfo_set生成的是一个特殊对象djangoapp.UserInfo.None,
      
      特别注意:通过_set进行反向查找时,必须要使用表名,而不是类名,即:有大小写区分
  2.通过牛逼的双下划线__反向连表操作
      obj = models.UserType.objects.filter(caption="管理员").values("caption","userinfo__name")
      print(obj)
      通过caption进行filter,在显示值的时候,使用了表名+__列名来进行反向连表操作

总结:在使用连表操作时(即:要展示多个表的数据时),都使用__来进行表之间的属性调用,正向查找使用外键,反向查找使用表名

   在表1调用表2的数据时,正向查找使用外键.属性,反向查找使用表名_set







补充:
  一对一连表操作时一对多连表操作的衍化

  1.使用外键一对一
      外键与外键关联的列使用唯一索引,即:
unique=True,这样两张表就一对一了

  2.使用models.OneToOneField创建一对一关系,原理就是1


猜你喜欢

转载自www.cnblogs.com/binpeng/p/8947888.html