django foreignkey(外键)的实现

yipeiwu_com6年前Python基础

foreignkey是一种关联字段,将两张表进行关联的方式,我们在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就是通过外键关联获取到了

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

pycharm执行python时,填写参数的方法

pycharm执行python时,填写参数的方法

1、按快捷键:alt+shift+F10调出运行窗口,之后选择Edit Configurations或者按0 2、输入参数,点击运行 以上这篇pycharm执行python时,填写参...

python访问系统环境变量的方法

本文实例讲述了python访问系统环境变量的方法。分享给大家供大家参考。具体如下: #-------------------------------- # Name: en...

python使用线程封装的一个简单定时器类实例

本文实例讲述了python使用线程封装的一个简单定时器类。分享给大家供大家参考。具体实现方法如下: from threading import Timer class MyTimer...

python连接sql server乱码的解决方法

vi /etc/freetds/freetds.conf 复制代码 代码如下:[global]# TDS protocol versiontds version = 8.0client...

Python datetime和unix时间戳之间相互转换的讲解

python datetime和unix时间戳之间相互转换 1、代码: import time import datetime # 1、datetime转unix时间戳...