• python---django使用数据库(orm)


    官方教点击此处 

    项目默认使用sqlite

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }

    并且在根目录中生成数据库文件

    db.sqlite3

    1.创建应用:官方规定,如果要使用模型,必须先创建一个app

    python manage.py startapp ts

    记得创建后去settings文件中查看应用是否添加进去,没有则自己添加,否则该应用中数据表创建失败

    INSTALLED_APPS = (
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'ts'
    )

    2.在ts目录中

     migrations#目录
         __init__.py
     __init__.py
     admin.py
     models.py
     tests.py
     views.py

    找到models文件,在这里面创建表

    from django.db import models
    
    # Create your models here.
    class User(models.Model):
        name=models.CharField(max_length=64)
      
       def __Str__(self):  #打印时直接打印数据,而不是显示类
         return self.name

    3.命令生成数据表:

    python manage.py makemigrations

    会自动知道我们的模型中的改变,并且开始创建数据库(对于多个应用,会排除已经创建过的,对于新的,会执行这个操作)

    Migrations for 'ts':
      0001_initial.py:
        - Create model User

    开始创建数据表:

    python manage.py migrate
    Operations to perform:
      Synchronize unmigrated apps: staticfiles, messages
      Apply all migrations: sessions, admin, ts, auth, blog, contenttypes
    Synchronizing apps without migrations:
      Creating tables...
        Running deferred SQL...
      Installing custom SQL...
    Running migrations:
      Rendering model states... DONE
      Applying ts.0001_initial... OK

    创建成功

    4.开始使用数据库

    from ts import models
    # Create your views here.
    
    def show_db(request):
        models.User.objects.create(
            name="test"
        )
    
        ret=models.User.objects.all()
        for item in ret:
            print(item.name)
        return HttpResponse("<h1>test over</h1>")

    记得在urls文件中修改路由

    from ts import views as v2
    urlpatterns
    = [ url(r'^test',v2.show_db) ]
  • 相关阅读:
    判断整除(动态规划,递推)
    Apollo 配置详细步骤(Windows环境)
    java的环境变量
    我的C++学习心得
    Maven实战_许晓斌
    深入理解计算机系统--中文版
    http 权威指南 -- http the definitive guide
    看原版英文和译版中文
    python 单元测试框架 pyunit
    在SQL Server 中创建外键
  • 原文地址:https://www.cnblogs.com/ssyfj/p/8626783.html
Copyright © 2020-2023  润新知