django中有一套类似于hibernate的orm框架,方便来处理与数据库相关的事务。要使用这个orm框架,首先需要设置好mysql的连接参数,在settings.py中有一个DATABASES的配置项,详情如下:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'mysite', # Or path to database file if using sqlite3. 'USER': 'user', # Not used with sqlite3. 'PASSWORD': 'password', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } }
from django.db import models class User(models.Model): name=models.CharField(max_length=255) password=models.CharField(max_length=32)
INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'mysite', # Uncomment the next line to enable the admin: # 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', )由于models.py就在mysite的根目录下,因此只要这里配置一个mysite就行了,其他的app是django自带的。然后执行syncdb命令:
python manage.py syncdb
+----------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(255) | NO | | NULL | | | password | varchar(32) | NO | | NULL | | +----------+--------------+------+-----+---------+----------------+
新增:
>>> from mysite.models import User >>> u = User(name='hello',password='world') >>> u.save()
>>> p = User.objects.filter(id=1) >>> p.update(name='name2') 1L
查询:
>>> p = User.objects.get(id=1) >>> p.name u'name2'
>>> p = User.objects.get(id=1) >>> p.delete()