基於Python的前後端分離學習筆記
阿新 • • 發佈:2020-10-29
一、建立後端步驟
1)建立Django工程
2)在終端執行命令python manage.py startapp market(market是package包,可以任意命名)
3)在setting.py檔案中,在INSTALLED_APPS中新增新建的檔名market,如:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'market',//新增新建的檔名 ]
4)右鍵工程,建立新的Python package檔案apps,將檔案market檔案移到apps中
5)在setting.py檔案中,新增程式碼:sys.path.insert(0, os.path.join(BASE_DIR, 'apps')) (別忘記import sys),如:
import os,sys # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve(strict=True).parent.parent sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))
6)建立ORM資料庫:
1、在models.py中建立類,如下(注意:類要繼承models.Model):
from django.db import models # Create your models here. class Stuff(models.Model): num = models.IntegerField(db_column="Num", primary_key=True, null=False) #編號,不允許為空,主鍵 name = models.CharField(db_column="Name", max_length=100, null=False) # 物品名稱,最長100個字元,不允許為空 image = models.CharField(db_column="Image", max_length=200, null=True) # 物品圖片 user = models.models.IntegerField(db_column="UNum", null=False) # 物品擁有者使用者編號 price = models.FloatField(db_column='Price', null=False) # 物品價格 count = models.IntegerField(db_column="Count", null=False) # 數量 # 在預設情況下,生成的表名:App_class, 如果要自定義 ,需要使用Class Meta來自定義 class Meta: managed = True db_table = "Stuff" class User(models.Model): num = models.IntegerField(db_column="UNum", primary_key=True, null=False) # 使用者編號,不允許為空,主鍵 name = models.CharField(db_column="UName", max_length=100, null=False) # 使用者暱稱,最長100個字元,不允許為空 telNum = models.CharField(db_column="Mobile", max_length=100) # 手機號碼 gender_choices = (('男', '男'), ('女', '女')) gender = models.CharField(db_column="Gender", max_length=100, choices=gender_choices) # 性別 address = models.CharField(db_column="Address", max_length=200) # 交易地點 class Meta: managed = True db_table = "User"
2、在資料庫中新建一個數據庫,如Market
3、在setting.py中配置資料庫,如下:
DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': BASE_DIR / 'db.sqlite3', # } 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'market', 'USER': 'root', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '3306', } }
4、在market的__init__.py中,新增如下程式碼:
import pymysql pymysql.version_info = (1, 4, 6, 'final', 0) # change mysqlclient version pymysql.install_as_MySQLdb()
5、在終端依次執行如下程式碼:
python manage.py makemigrations
python manage.py migrate