博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
model相关
阅读量:4973 次
发布时间:2019-06-12

本文共 9937 字,大约阅读时间需要 33 分钟。

链接数据库

 与数据库相关的两条命令:

1 python manage.py makemigrations    2 python manage.py migrate

设置数据库

 mysql:

单表操作

1 DATABASES = { 2  3     'default': { 4  5         'ENGINE': 'django.db.backends.mysql', 6  7         'NAME': 'blog',    #你的数据库名称 8  9         'USER': 'root',   #你的数据库用户名10 11         'PASSWORD': '', #你的数据库密码12 13         'HOST': '', #你的数据库主机,留空默认为localhost14 15         'PORT': '3306', #你的数据库端口16 17     }18 19 } 若出现连接错误::

 

 

在models.py里边建立模型

 

 

 

关于数据类型的说明:

 

 操作相关

导入

 

增:

1 增加:2 (1)bookobj=models.Book(title='一本小说',aithor='yuan')3         bookobj.save()4 5 (2)abook=models.Book.create(title='一本小说',....)6 abook是返回的一个对象

 

查:

  

1 查询全部:models.Book.objects.all()2 查询符合条件的:models.Book.objects.filter(bid=sel_id)3 符合条件的第一条:models.Book.objects.filter(bid=sel_id).first()

 1 models.Book.objects.filter(bid=1).update( name='hahah')

修改哪一个字段改哪一个字段

 

 

 1 models.Book.objects.filter(bid=del_id).delete() 

查询方法API:
1 # 查询方法API: 2  3  4     # 1  all: models.表名.objects.all() 5     #  6     book_all=models.Book.objects.all()  # 结果是querySet集合    [model对象,....] 7     #print(book_all) # 
,
,
]> 8 9 # 2 filter: models.表名.objects.filter() # 结果是querySet集合 [model对象,....]10 11 # ret1=models.Book.objects.filter(author="yuan") # #
,
]>12 #ret2=models.Book.objects.filter(nid=1) #
]>13 # ret2=models.Book.objects.filter(author="yuan",price=123) #
]>14 # print(ret2)15 16 # 3 get models.表名.objects.get() # model对象17 18 # ret3=models.Book.objects.get(author="yuan")19 # print(ret3.price)20 21 22 # exclude : 排除条件23 # ret4=models.Book.objects.exclude(author="yuan")24 # print(ret4)25 26 # values方法27 # ret=models.Book.objects.filter(author="yuan").values("title","price")28 # print(ret)#
29 30 # ret = models.Book.objects.filter(author="yuan").values_list("title", "price")31 # print(ret) #
32 33 # ret=models.Book.objects.filter(author="yuan").values("author").distinct()34 # print(ret)35 36 # count方法37 # ret=models.Book.objects.filter(author="yuan").count()38 # print(ret)39 40 # first 方法41 # ret = models.Book.objects.all().first()42 # print(ret)43 44 # exists方法45 # if models.Book.objects.all().exists():46 # print("exists")47 # else:48 # print("nothing")49 50 51 52 ret=models.Book.objects.filter(price__gt=100)53 ret=models.Book.objects.filter(price__gte=99) # 大于等于54 55 #ret=models.Book.objects.filter(publishDate__year=2017,publishDate__month=10)56 #ret=models.Book.objects.filter(author__startswith="张")
1 # 查询方法API: 2  3  4     # 1  all: models.表名.objects.all() 5     #  6     book_all=models.Book.objects.all()  # 结果是querySet集合    [model对象,....] 7     #print(book_all) # 
,
,
]> 8 9 # 2 filter: models.表名.objects.filter() # 结果是querySet集合 [model对象,....]10 11 # ret1=models.Book.objects.filter(author="yuan") # #
,
]>12 #ret2=models.Book.objects.filter(nid=1) #
]>13 # ret2=models.Book.objects.filter(author="yuan",price=123) #
]>14 # print(ret2)15 16 # 3 get models.表名.objects.get() # model对象17 18 # ret3=models.Book.objects.get(author="yuan")19 # print(ret3.price)20 21 22 # exclude : 排除条件23 # ret4=models.Book.objects.exclude(author="yuan")24 # print(ret4)25 26 # values方法27 # ret=models.Book.objects.filter(author="yuan").values("title","price")28 # print(ret)#
29 30 # ret = models.Book.objects.filter(author="yuan").values_list("title", "price")31 # print(ret) #
32 33 # ret=models.Book.objects.filter(author="yuan").values("author").distinct()34 # print(ret)35 36 # count方法37 # ret=models.Book.objects.filter(author="yuan").count()38 # print(ret)39 40 # first 方法41 # ret = models.Book.objects.all().first()42 # print(ret)43 44 # exists方法45 # if models.Book.objects.all().exists():46 # print("exists")47 # else:48 # print("nothing")49 50 51 52 ret=models.Book.objects.filter(price__gt=100)53 ret=models.Book.objects.filter(price__gte=99) # 大于等于54 55 #ret=models.Book.objects.filter(publishDate__year=2017,publishDate__month=10)56 #ret=models.Book.objects.filter(author__startswith="张")
相关的API部分

 

多表查询

建立多表,以图书管理系统为例

 

1 from django.db import models 2  3 # Create your models here. 4 class Book(models.Model): 5     #book表 6     bid=models.AutoField(primary_key=True) 7  8     title=models.CharField(max_length=42) 9 10     publishDate=models.DateField()11 12     price=models.DecimalField(max_digits=5,decimal_places=2)13 14     author=models.ManyToManyField('Author')15 16     press = models.ForeignKey('Press')17     # read_many = models.OneToOneField('Read_many')18     def  __str__(self):19         return self.title20 21 22 class Author(models.Model):23     #作者表24     name=models.CharField(max_length=32)25     tel=models.IntegerField()26     # press=models.OneToOneField(to='Press')27     def __str__(self):28         return self.name29 30 class Press(models.Model):31     #出版社表32     press_name=models.CharField(max_length=32)33     press_addr=models.CharField(max_length=32)34     def __str__(self):35         return self.press_name36 37 # class Read_many(models.Model):38 #     #阅读相关表39 #     wordNum=models.IntegerField(default=0)40 #     readNum=models.IntegerField(default=0)
models代码
1 from django.shortcuts import render,redirect,HttpResponse  2 from app01 import models  3   4   5 import datetime,time  6 # Create your views here.  7 def Dashboard(request):  8     return render(request, 'Dashboard.html')  9  10 def base(request): 11     return render(request,'base.html') 12  13 def insert_book(request): 14  15     return redirect('/info/') 16  17  18 def book_info(request): 19     book_info_all=models.Book.objects.all() 20     # try: 21     #     print('看作者:', book_info_all.first().author.all()) 22     # except Exception: 23     #     print('这里出错了') 24     list_name = models.Author.objects.all().values_list('id','name') 25     # print('作者的名字', list_name) 26     list_press = models.Press.objects.all().values_list('id','press_name') 27     # print('出版社:', list_press) 28     return render(request,'BookInfo.html',{
'book_info_all':book_info_all,'list_name':list_name,'list_press':list_press}) 29 30 31 # def tianjia(request): 32 # list_name=models.Author.objects.all().values_list('name') 33 # print('作者的名字',list_name) 34 # list_press=models.Press.objects.all().values_list('press_name') 35 # print('出版社:',list_press) 36 # # for i in list_name: 37 # # print(i[0]) 38 # return render(request,'tianjia.html',{'list_name':list_name,'list_press':list_press}) 39 40 41 42 def tianjia(request): 43 print('这里是添加的东西',request.POST) 44 book_obj=models.Book.objects.create( 45 title=request.POST.get('title'), 46 publishDate=request.POST.get('date'), 47 price=request.POST.get('price'), 48 press_id=request.POST.get('press') 49 ) 50 # print('title',request.POST.get('title')) 51 # print('date',request.POST.get('date')) 52 # print('price',request.POST.get('price')) 53 54 # author_id=request.POST.get('author') 55 author_id=request.POST.getlist('author') 56 print('author_id',author_id) 57 for author_one in author_id: 58 print('第一' * 10) 59 print(models.Author.objects.filter(id=author_one)) 60 book_obj.author.add(models.Author.objects.filter(id=int(author_one))[0]) 61 print(models.Author.objects.filter(id=author_one)) 62 # print('第2' * 10,models.Author.objects.filter(id=author_one)) 63 # press_id=request.POST.get('press') 64 # print('第3' * 10) 65 # book_obj.press=models.Press.objects.filter(id=press_id) 66 67 return redirect('/book/') 68 69 70 71 72 73 def del_id(request,book_id): 74 models.Book.objects.filter(bid=book_id).delete() 75 return redirect('/book/') 76 77 78 79 def bianji(request,book_id): 80 edit_info=models.Book.objects.filter(bid=book_id).first() 81 # print(edit_info.author.all().values_list('id','name')) 82 eau=edit_info.author.all().values_list('id','name') 83 item_l=[] 84 for item_id in eau: 85 item_l.append(item_id[0]) 86 # print('作者的名字eau',eau) 87 # print( '66666666666666666+',models.Author.objects.all().values()) 88 list_name=edit_info.author.all().values_list('id','name') 89 list_name = models.Author.objects.exclude(id__in=item_l).values_list('id','name') 90 # print('作者的名字', list_name) 91 list_press = models.Press.objects.exclude(id=edit_info.press_id).values_list('id','press_name') 92 93 return render(request,'info_edit.html',{
'edit_info':edit_info,'list_name':list_name,'list_press':list_press,'eau':eau}) 94 95 # 96 def info_edit(request): 97 book_obj = models.Book.objects.filter(bid=request.POST.get('bid')) 98 book_obj.update( 99 title=request.POST.get('title'),100 publishDate=request.POST.get('date'),101 price=request.POST.get('price'),102 press_id=request.POST.get('press')103 )104 book_obj[0].author.clear()105 # for au_id in request.POST.getlist('author'):106 auobj=models.Author.objects.filter(id__in=request.POST.getlist('author'))107 for add_obj in auobj:108 book_obj[0].author.add(add_obj)109 print('查询出来的',auobj)110 print('book_obj.authorList',book_obj[0].author.all())111 # print(request.POST.get('title'))112 return redirect('/book/')
View代码
1 from django.conf.urls import url 2 from django.contrib import admin 3 from app01 import views 4  5 urlpatterns = [ 6     url(r'^admin/', admin.site.urls), 7     url(r'^Dashboard/', views.Dashboard), 8     url(r'^base/', views.base), 9     url(r'^book/', views.book_info),10     url(r'^tianjia/', views.tianjia),11     url(r'^del/(\d+)', views.del_id),12     url(r'^bianji/(\d+)', views.bianji),13     url(r'^info_edit/', views.info_edit),14 ]
urls

 

*

*

*

*

*

**

*

 

*

 

转载于:https://www.cnblogs.com/xiesibo/p/7731083.html

你可能感兴趣的文章
执行了的程序,才是你的程序.
查看>>
struts2.x + Tiles2.x读取多个xml 配置文件
查看>>
表单校验之datatype
查看>>
python第六篇文件处理类型
查看>>
ubuntu16系统磁盘空间/dev/vda1占用满的问题
查看>>
grid网格布局
查看>>
JSP常用标签
查看>>
九涯的第一次
查看>>
处理器管理与进程调度
查看>>
向量非零元素个数_向量范数详解+代码实现
查看>>
java if 用法详解_Java编程中的条件判断之if语句的用法详解
查看>>
matlab sin函数 fft,matlab的fft函数的使用教程
查看>>
mysql adddate()函数
查看>>
mysql sin() 函数
查看>>
单片机复位电路
查看>>
php json_decode失败,返回null
查看>>
3-day3-list-truple-map.py
查看>>
Edit控件显示多行文字
查看>>
JS第二周
查看>>
dataTable.NET的search box每輸入一個字母進行一次檢索的問題
查看>>