zoukankan      html  css  js  c++  java
  • django 连接mysql 数据库

    1、新建一个mysite项目:django-admin startproject mysite 

    2、进入项目目录,新建一个app : python manage.py startapp polls

    3、安装mysqlclient :pip install mysqlclient

    4、在settings.py  database中设置数据库连接配置

    DATABASES = {
    'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'my_web',
    'USER': 'root',
    'PASSWORD': 'password',
    'HOST': '127.0.0.1',
    'PORT': '3306',
    }
    }

    5、执行命令: python manage.py migrate

    在数据库中自动创建web系统使用到的表

    6、编辑polls/models.py文件内容

    from django.db import models
    
    
    class Question(models.Model):
        question_text = models.CharField(max_length=200)
        pub_date = models.DateTimeField('date published')
    
    
    class Choice(models.Model):
        question = models.ForeignKey(Question, on_delete=models.CASCADE)
        choice_text = models.CharField(max_length=200)
        votes = models.IntegerField(default=0)

    7、修改mysite/settings.py 文件INSTALLED_APPS 添加  'polls.apps.PollsConfig',

    INSTALLED_APPS = [
    'polls.apps.PollsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    ]


    
    
    7、执行命令:python manage.py makemigrations polls

    Migrations for 'polls':
      polls/migrations/0001_initial.py:
        - Create model Choice
        - Create model Question
        - Add field question to choice

    8、执行命令:python manage.py sqlmigrate polls 0001

     9 再执行python manage.py migrate 命令,创建数据库表

     
  • 相关阅读:
    洛谷 P1226 【模板】快速幂||取余运算 题解
    洛谷 P2678 跳石头 题解
    洛谷 P2615 神奇的幻方 题解
    洛谷 P1083 借教室 题解
    洛谷 P1076 寻宝 题解
    洛谷 UVA10298 Power Strings 题解
    洛谷 P3375 【模板】KMP字符串匹配 题解
    Kafka Shell基本命令
    Mybatis与Hibernate的详细对比
    MyBatis简介
  • 原文地址:https://www.cnblogs.com/testway/p/7435328.html
Copyright © 2011-2022 走看看