django foreignkey(外键)的实现
人气:0foreignkey是一种关联字段,将两张表进行关联的方式,我们在dodels.py里写入要生成的两张表:
class Usergroup(models.Model): uid=models.AutoField(primary_key=True) caption=models.CharField(max_length=64,null=True) ctime=models.DateField(auto_now_add=True,null=True) uptime=models.DateField(auto_now=True,null=True) class Userinfo(models.Model): username=models.CharField(max_length=32,blank=True) password=models.FileField(max_length=60,help_text='pwd') email=models.CharField(max_length=60) test=models.EmailField(max_length=20,null=True,error_messages={'invalid':'shurumima'}) user_group=models.ForeignKey('Usergroup',to_field='uid',default=1) #这里与上面的Usergroup表的uid进行关联,默认取到uid=1的行) user_type_choices=( (1,'superuser'), (2,'commonuser'), (3,'com-commonuser'), ) user_type_id=models.IntegerField(choices=user_type_choices,default=1)
运行下面两条命令:
C:\Users\Liujiangbu.GLOBALE.001\PycharmProjects\untitled3>python manage.py makemigrations
C:\Users\Liujiangbu.GLOBALE.001\PycharmProjects\untitled3>python manage.py migrate
编辑app项目的views.py加入下面两段:
def user_info(request): if request.method == "GET": #userlist = test.objects.all() userlist2=models.Userinfo.objects.all() #获取Userinfo表的所有信息 # return render(request,'userinfo.html',{'userlist':userlist}) return render(request, 'userinfo.html', {'userlist2': userlist2}) #模板引用 elif request.method == "POST": u = request.POST.get('user') pp= request.POST.get('pwd') #test.objects.create(username=u,depno=pp) models.Userinfo.objects.create(username=u,password=pp,user_group_id=1) return HttpResponse("<p>注册成功</p>")
模板中创建userinfo.html,并加入下面内容:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>666666(runoob.com)</title> </head> <body style="background-color:silver"> <div> <div style="color:#00FF00"> <a class="menu" href="/home-bak" rel="external nofollow" >是爷们儿就点下 </a> <br /> <a class="menu" href="/group" rel="external nofollow" >是爷们儿就洅点下 </a> </div> <div style="color:#666644"> <h3>添加主机</h3> <form method="POST" action="/userinfo"> <input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}"> <input type="text" name="user"> <input type="text" name="pwd"> <input type="submit" name="添加"> </form> <h3>主机列表</h3> <ul> {% for i in userlist2 %} <li><a href="/datail" rel="external nofollow" >{{ i.username }}</a> <span>{{ i.user_group.caption }}</span> </li> {% endfor %} </ul> </div> </div> </body> </html>
然后添加url:
执行项目:
在空白处写入内容,会自动添加到数据库中:
表中的DBA就是通过外键关联获取到了
您可能感兴趣的文章:
加载全部内容