配置models文件
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class UserMessage(models.Model):
#设置主键,必须加default属性
object_id = models.CharField(default="", max_length=20, primary_key=True, verbose_name=u"主键")
name = models.CharField(max_length=20, verbose_name=u"用户名")
email = models.EmailField(verbose_name=u"邮箱")
address = models.CharField(max_length=100, verbose_name="联系地址")
message = models.CharField(max_length=500, verbose_name="留言信息")
class Meta:
verbose_name = u"用户留言信息"
verbose_name_plural = verbose_name #如果不指定这个,保存内容会自动加一个s
# db_table = "user_message" #设置数据表名称
# ordering = "-object_id" #默认排序
生成更改
可以在数据库看到生成的新表
数据库的查询操作
views文件修改
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from models import UserMessage
# Create your views here.
def getform(request):
#数据库查询
all_messages = UserMessage.objects.all() #查询所有
for message in all_messages:
print message.name, message.email,message.object_id,message.message,message.address
return render(request,'message_form.html')
数据库添加测试内容
运行web后查看到调试信息,和上面数据库的一样
不对所有数据查询,也可以对某几种属性查询,使用如下语句查询,下面两个条件是与的关系
all_messages = UserMessage.objects.filter(name = "神秘藏宝室",address="洛阳")
增加数据库操作
#增加数据库
user_message = UserMessage()
user_message.name = "神秘藏宝室2"
user_message.email = "test@xx.com"
user_message.object_id = "testid2"
user_message.message = "helloworld2"
user_message.address = "洛阳"
user_message.save()
重新运行项目,刷新网页,在数据库能看到数据了
删除数据库很简单
#数据库查询
all_messages = UserMessage.objects.filter(name = "神秘藏宝室",address="洛阳")
all_messages.delete() #全部删除
for message in all_messages:
print message.name, message.email,message.object_id,message.message,message.address
message.delete() #单条删除