Django-Models-多表查询
-
表关系
- 一对多:models.ForeignKey(其他表)
- 多对多:models.ManyToManyField(其他表)
- 一对一:models.OneToOneField(其他表)
-
一对多关系(从表为userinfo和主表usertype)
-
设置外键
user_type=models.ForeignKey(to="usertype",to_field="id",default=1,on_delete= models.CASCADE)
此时、主表为usertype,从表为userinfo.注意在数据库中表明为“模块名_类名的小写形势”。加入模块名为userinfo,这两个表名分贝为“user_usertype”和"user_userinfo".
在从表中会产生一个新的字段:user_type_id.但注意user_type代表的是主表usertpye对象。注意加上on_delete= models.CASCADE
-
models.CASCADE,删除关联数据,与之关联也删除
-
models.DO_NOTHING,删除关联数据,引发错误IntegrityError
-
models.PROTECT,删除关联数据,引发错误ProtectedError
-
models.SET_N
-
-