django 02--与数据库交互
创建数据库
mysql -u root -p
CREATE DATABASE villa DEFAULT CHARSET=utf8;
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES ON villa.* TO 'vamei'@'localhost' IDENTIFIED BY 'vameiisgood';
配置setting.py
DATABASES = {
'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'ENGINE': 'django.db.backends.mysql',
'NAME': 'villa',
'USER': 'vamei',
'PASSWORD': 'vameiisgood',
'HOST': 'localhost',
'PORT': '3306',
}
}
windows下如果使用的是virtualenv虚拟环境的话,可能需要安装pip install mysqlclient
, 测试一下是否正常:>>>import MySQLdb
同步数据库
python manage.py migrate
创建模型
修改west/models.py
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Character(models.Model):
name = models.CharField(max_length=200)
def __unicode__(self):
return self.name
再次同步数据库
python manage.py makemigrations west
python manage.py migrate
Django Shell
$python manage.py shell
Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> import django
>>> from west.models import Character
>>> Character.objects.all()
<QuerySet []>
>>> c = Character(name='John')
>>> c.save()
>>> c.id
1L
>>> c.name
'John'
>>> c.name = 'Vamei'
>>> c.save()
>>> Character(name='Django').save()
>>> Character(name='John').save()
>>> Character.objects.all()
<QuerySet [<Character: Vamei>, <Character: Django>, <Character: John>]>
增加一个页面,显示所有人员
修改west/views.py
def staff(request):
staff_list = Character.objects.all()
staff_str = map(str, staff_list)
return HttpResponse("<p>" + ' '.join(staff_str) + "<p>")
修改west/urls.py
url(r'^staff/', views.staff),