Django与ORM回顾
Django知识简单回顾
一、数据库配置
import pymysql pymysql.install_as_MySQLdb() DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '数据库名', 'USER': '账号', 'PASSWORD': '密码', 'HOST': '如果是127.0.0.1,该配置可以省略', "PORT": 3306, # 如果是3306,该配置可以省略 }
二 、路由分发
主路由: from django.conf.urls import url, include urlpatterns = [ # ... url(r'^api/', include('api.urls')) # /api/test/ ] 分路由: from django.conf.urls import url from . import views urlpatterns = [ url(r'^users/$', views.UserAPIview.as_view()) ]
ORM配置回顾
models.py
from django.db import models class User(models.Model): SEX_CHOICES = ((0, '男'), (1, '女')) #元组效率比列表高一些 name = models.CharField(max_length=64, verbose_name='姓名') age = models.IntegerField() height = models.DecimalField(max_digits=5, decimal_places=2, default=0) sex = models.IntegerField(choices=SEX_CHOICES, default=0) # sex = models.CharField(choices=[('0', '男'), ('1', '女')]) icon = models.ImageField(upload_to='icon', default='icon/default.png')
settings.py
# root 就将文件夹添加到os.path中 MEDIA_ROOT = os.path.join(BASE_DIR,'media') # url就是配置路由/路由名 MEDIA_URL = '/media/'
主路由最下方
from django.views.static import serve from django.conf import settings urlpatterns = [ # icon/default.png => path变量 # media/(?P<path>.*) 是指media/后面所有东西都能匹配 # document_root 必须指向 icon/default.png 所在路径 - media文件夹路径 url(r'^media/(?P<path>.*)', serve,{'document_root':settings.MEDIA_ROOT}), ]