django数据库
时间的设定
from django.db import models
import django.utils.timezone as timezone
class Doc(models.Model):
add_date = models.DateTimeField('保存日期',default = timezone.now)
mod_date = models.DateTimeField('最后修改日期', auto_now = True
html页面从数据库中读出DateTimeField字段时,显示的时间格式和数据库中存放的格式不一致,比如数据库字段内容为2016-06-03 13:00:00,但是页面显示的却是Apr. 03, 2016, 1 p.m.
为了页面和数据库中显示一致,需要在页面格式化时间,需要添加<td>{{ infor.updatetime|date:"Y-m-d H:i:s" }}</td> 类似的过滤器。刷新页面,即可正常显示。
from django.db import models
from datetime import datetime
import django.utils.timezone as timezone
# Create your models here.
# 1: 简单用户表 tb_user:
# id , username,userpaw
class user(models.Model):
user_name = models.CharField(max_length=20)
user_paw = models.CharField(max_length=20)
def __str__(self):
return (self.user_name, self.user_paw)
# 2: 用户详细信息表 tb_userinfo
# id,userid , email , homepage , phone , address ...
class user_info(models.Model):
user_id = models.ForeignKey("user", on_delete=models.CASCADE)
email = models.CharField(max_length=30)
phone = models.CharField(max_length=16)
sex = models.CharField(max_length=5)
def __str__(self):
return (self.user_id, self.email, self.phone, self.sex)
# 3: 论坛主题表 tb_bbs
# id , userid , title , ip , count ,create_time, up
class bbs(models.Model):
user_id = models.ForeignKey("user",on_delete=models.CASCADE)
title = models.CharField(max_length=50)
create_time = models.DateTimeField()
count = models.IntegerField(default=timezone.now)
up = models.IntegerField()
def __str__(self):
return (self.user_id, self.title, self.create_time, self.count, self.up)
# 4: 论坛内容标 tb_bbs_content (此表可按照bbsid进行分表存储)
# id,bbsid , content;
class bbs_content(models.Model):
bbs_id = models.ForeignKey("bbs", on_delete=models.CASCADE)
content = models.CharField(max_length=200)
def __str__(self):
return (self.bbs_id, self.content)
# 5: 论坛回复表 tb_bbs_reply (此表可按照bb_sid进行分表存储)
# id , bbs_id , user_id , content , time , ip
class bbs_reply(models.Model):
bbs_id = models.ForeignKey("bbs", on_delete=models.CASCADE)
user_id = models.ForeignKey("User", on_delete=models.CASCADE)
content = models.CharField(max_length=150)
time = models.DateTimeField(default=timezone.now)
def __str__(self):
return (self.bbs_id, self.user_id, self.content, self.time)
表操作
表记录的添加
方式一:
Book()
b=Book(name="python基础",price=99,author="yuan",pub_date="2017-12-12")
b.save()
方式二:
Book.objects.create()
Book.objects.create(name="老男孩linux",price=78,author="oldboy",pub_date="2016-12-12")
表记录的修改
方式一:
b=Book.objects.get(author="oldboy")
b.price=120
b.save()
方式二:
#update是QuerySet
Book.objects.filter(author="yuan").update(price=999)
表记录的删除:
Book.objects.filter(author="oldboy").delete()
表记录的查询(重点):
book_list = Book.objects.filter(id=2)
book_list=Book.objects.exclude(author="yuan").values("name","price")
book_list=Book.objects.all()
book_list = Book.objects.all()[::2]
book_list = Book.objects.all()[::-1]
#first,last,get取到的是一个实例对象,并非一个QuerySet的集合对象
book_list = Book.objects.first()
book_list = Book.objects.last()
book_list = Book.objects.get(id=2)#只能取出一条记录时才不报错
ret1=Book.objects.filter(author="oldboy").values("name")
ret2=Book.objects.filter(author="yuan").values_list("name","price")
book_list= Book.objects.all().values("name").distinct()
book_count= Book.objects.all().values("name").distinct().count()
模糊查询 双下划线__
book_list=Book.objects.filter(name__icontains="P").values_list("name","price")
book_list=Book.objects.filter(id__gt=5).values_list("name","price")
多表操作(一对多):
#添加记录
#publish_id=2
Book.objects.create(name="linux运维",price=77,pub_date="2017-12-12",publish_id=2)
#publish=object
Book.objects.create(name="GO",price=23,pub_date="2017-05-12",publish=publish_obj)
#查询记录(通过对象)
正向查询:
book_obj=Book.objects.get(name="python")
pub_obj=book_obj.publish----》书籍对象对应的出版社对象
pub_obj.name
反向查询:
pub_obj = Publish.objects.filter(name="人民出版社")[0]
pub_obj.book_set.all().values("name","price")
#查询记录(filter values 双下划线__)
#人民出版社出版过的书籍与价格
ret=Book.objects.filter(publish__name="人民出版社").values("name","price")
#python这本书出版社的名字
ret2=Publish.objects.filter(book__name="python").values("name")
#python这本书出版社的名字
ret3=Book.objects.filter(name="python").values("publish__name")
#北京的出版社出版书的名字
ret4=Book.objects.filter(publish__city="北京").values("name")
#2017年上半年出版过书的出版社的名字
ret5=Book.objects.filter(pub_date__lt="2017-07-01",pub_date__gt="2017-01-01").values("publish__name")
多表操作(多对多):
创建多对多的关系 author= models.ManyToManyField("Author")(推荐)
书籍对象它的所有关联作者 obj=book_obj.authors.all()
绑定多对多的关系 obj.add(*QuerySet)
obj.remove(author_obj)
如果想向第三张表插入值的方式绑定关系: 手动创建第三张表
# class Book_Author(models.Model):
# book=models.ForeignKey("Book")
# author=models.ForeignKey("Author")
Book_Author.objects.create(book_id=2,author_id=3)
掌握:通过 filter values (双下换线)进行多对多的关联查询(形式和一对多)
from django.db import models
班级:
id name
1 3班
2 6班
class School:
name = models.CharField(max_length=32)
class Classes(models.Model):
"""
班级表,男
"""
titile = models.CharField(max_length=32)
# m = models.ManyToManyField('Teachers') # 多对多
# sch = models.ForeignKey(School)
老师:
id title
1 Alex
2 老妖
3 瞎驴
4 Eric
class Teachers(models.Model):
"""
老师表,女
"""
name = models.CharField (max_length=32)
学生
id username age gender cs_id
1 东北 18 男 1
2 东北1 118 男 2
2 东北1 118 男 1
class Student(models.Model):
"""
学生表
"""
username = models.CharField(max_length=32)
age = models.IntegerField()
gender = models.BooleanField()
cs = models.ForeignKey(Classes) #
示例:
- 所有学生的姓名以及其所在班级名称,QuerySet
stu_list = Student.objects.all()
select * from tb;
[obj,obj,obj,obj]
stu_list = Student.objects.all().values("id",'username')
select id,username from tb;
[{"id":1,'username':'xx'},{id:'',username:''}]
stu_list = Student.objects.all().values_list("id",'username')
[(1,'root'), (2,'alex')]
stu_list = Student.objects.all().values('username',"cs__name")
for row in stu_list:
print(row['username'],row['cs__name'])
stu_list = Student.objects.all().values('username',"cs__titile",“cs__fk__name”)
- 找到3班的所有学生
Student.objects.filter(cs__name='3班')
obj = Classes.objects.filter(name='3班').first()
1. 类代表数据库表
2. 类的对象代指数据库的一行记录
3. FK字段代指关联表中的一行数据(类的对象)
4.
- 正向:fk字段 (*****)
- 反向:小写类名_set(默认) ==> related_name='ssss'
5. 谁是主表?就全部列出其数据
models.Student.objects.all().values('username', 'cs__titile')
models.Classes.objects.all().values('titile', 'ssss__username')
4. M2M字段,自动生成第三张表;依赖关联表对第三张表间接操作
对话框添加,删除,修改:
添加:
Ajax偷偷向后台发请求:
1. 下载引入jQuery
2.
$.ajax({
url: '/add_classes.html',
type: 'POST',
data: {'username':'root','password': '123'},
success:function(arg){
// 回调函数,arg是服务端返回的数据
}
})