class UsserGroup(models.Model): uid = models.AutoField(primary_key=True) caption = models.CharField(max_lenght=32, unique=True) class UserInfo(models.Model): username = models.CharField(max_length=32,blank=True,verbose_name = '用户名') password = models.CharField(max_length=60, help_text='pwd') #外键 to_field不写也行,以默认主键 会将user_group生成为user_group_id 数字 user_group = models.ForeignKey('UserGroup', to_field = 'uid',default=1,on_delete=models.CASCADE) 特殊地方 user_group 封装为一个对象 可以直接调用UserGroup的参数 即user_group.caption 而user_group_id为数字 user_list = Userinfo.objects.all() for row in user_list: print(row.user_group_id) print(row.user_group.uid) print(row.user_group.caption) #一对多 #user_list = models.UserInfo.object.all( username = 'root' password='123', user_group_id = '1' #直接用表里面user_group中 让他设置为user_group_id ) 让用户选择部门 group_list = models.UserGroup.object.all() 在html里写 <form> <select name = 'group_id'> {% for item in group_list %} <option value='{{item.uid}}'>{{ item.caption }}</option> {% endfor %} </select> <form> 一对多: a.外键 b.外键字段_id c. models.tb.object.create(name='root'),user_group_id = 1 d. userlist = models.tb.object.all() for row in userlist: row.id row.user_group_id row.user_group.caption