Djiango框架之添加表记录

 

 

 

from django.db import models

# Create your models here.
class Book(models.Model):
id = models.AutoField(primary_key=True) #自增类型
title = models.CharField(max_length=32) #字符串
price = models.DecimalField(max_digits=8,decimal_places=2) #浮点数
pub_date = models.DateField() #日期类型年月日
pub_dates = models.DateTimeField #日期类型精确到时分秒

class Meta:
db_table = "book"

 

 

 

"""mysite URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,re_path,include
from views.py import get_ncov,article,articleByMonth,get_timer,test
urlpatterns = [
#urls路由控制器
path('article/2012', article),
re_path('article/\d+', article),
re_path('^article/\d+$', article),
re_path('^article/\d{4}$', article),
#无名分组
# /article/2012
re_path('^article/(\d{4})$', article), # article(request,2012)
# /article/2012/12
re_path('^article/(\d{4})/\d{1,2}$', articleByMonth), # articleByMonth(request,2012,12)

#有名分组
re_path('^article/(?P<year>\d{4})/(?P<month>\d{1,2}$', articleByMonth), # articleByMonth(request,year=2012,month=12)


#路由的include分发机制
path('app01/', include('app01.urls')),
path("book/",include("book.urls")),

#path('app01/admin/', admin.site.urls),
#path('app01/timer/', get_timer),
#path('app01/test/', test),
#path('app01/2019ncov/', get_ncov),

'''
re.findall('article/\d+',"article/2011abc")
re.findall('article/\d+',"abc/article/2011abc")
re.findall('article/\d+',"abc/article/abc/2011abc")
'''

]

 

 

"""mysite URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, re_path, include
from book.views import add_book
urlpatterns = [

path('add_book', add_book),



]

 

 

from django.shortcuts import render,HttpResponse
from book.models import Book
import datetime
# Create your views here.
def add_book(request):

#添加书籍
# 方式1
#date = datetime.date(year=2012,month=12,day=12)
#book = Book(title="xiyouji", price=199, pub_date=date)
book = Book(title="xiyouji",price=199,pub_date="2012-12-12")
print(book.id) #None
book.save() #执行sql
print(book.id) # 3

# 方式2
book = Book.objects.create(title="sanguoyanyi",price=299,pub_date="2011-11-11")
print(book.id)
print(book.price)



return HttpResponse("添加书籍")

 

 

"""
Django settings for mysite project.

Generated by 'django-admin startproject' using Django 3.2.

For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-#zhfyd!i*izc78turi%swhgq9q5-jd*1syzzj6m6pfupuqvire'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01.apps.App01Config'
"book.apps.BookConfig"
]

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

WSGI_APPLICATION = 'mysite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

#DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': BASE_DIR / 'db.sqlite3',
# }
#}

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': '127.0.0.1', # 数据库主机
'PORT': '3306', # 数据库端口
'USER': 'root', # 数据库用户名
'PASSWORD': '123456', #数据库用户密码
'NAME': 's32', # 数据库名称
}
}

# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]


# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

STATIC_URL = '/static/'

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

(1)生成迁移文件

所谓的迁移文件, 是类似模型类的迁移类,主要是描述了数据表结构的类文件.

1
python manage.py makemigrations

(2)同步到数据库中

1
python manage.py migrate

 

posted @ 2022-07-07 21:56  呼长喜  阅读(73)  评论(0编辑  收藏  举报