zoukankan      html  css  js  c++  java
  • 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) ]
  • 相关阅读:
    linux之SQL语句简明教程---主键,外来键
    [LeetCode][Java] Best Time to Buy and Sell Stock IV
    S3C2440 IIS操作 uda134x录放音
    Cocos2d-x 3.0 打造一个全平台概念文件夹
    Irrlicht 3D Engine 笔记系列之 教程4
    Swift----编程语言语法
    Nginx优化指南+LINUX内核优化+linux连接数优化+nginx连接数优化
    windows平台是上的sublime编辑远程linux平台上的文件
    POJ 2249-Binomial Showdown(排列组合计数)
    Linux 循环
  • 原文地址:https://www.cnblogs.com/ssyfj/p/8626783.html
Copyright © 2011-2022 走看看