【2014-08-19】Django自学笔记:MVC

发布时间:2026/9/1 7:26:35
【2014-08-19】Django自学笔记:MVC [历史归档]本文原发布于 cstriker1407.info 个人博客内容为历史存档仅供参考。发布时间2014-08-19 标题Django自学笔记MVC分类编程 / web / Django 标签django·mvcDjango自学笔记MVC备注数据库配置新建一个APP增加存储结构数据库操作简单的插入和查询条件查找精确查找模糊查找排序与逆向排序:复合查询更新删除备注最近自学了下Django这里笔记下学习记录。备注1 学习记录中的代码和资料参考自网络教程【 http://djangobook.py3k.cn/2.0/ 】和【 http://www.djangobook.com/en/2.0/ 】版权归原作者所有。2 小弟第一次接触到Django本笔记可能有错误还请各位路过的大牛们给予指点。3 由于教程年代比较久远了而且Django不同版本改动很大这里作者的学习笔记是基于【python2.7.8 django1.6.5】实现的。4 由于时间关系学习记录里有的地方记得比较乱以后有时间再整理下吧。数据库配置为了简单起见这里使用默认的Sqlite来作为数据库那么默认建立的工程已经配置好了数据库~~这里首先看下settings.py中关于数据库的配置DATABASES{default:{ENGINE:django.db.backends.sqlite3,NAME:os.path.join(BASE_DIR,db.sqlite3),}}这里可以知道数据库的地址为D:\Documents\pythons\HelloDjango\db.sqlite3在settings.py上一级和manage.py同一级。如下图测试数据库是否正确配置启动命令行D:\Documents\pythons\HelloDjangopython manage.py shell 。。。。。。fromdjango.dbimportconnectioncursorconnection.cursor()如果没有错误就说明配置正确。新建一个APP启动CMD输入命令D:\Documents\pythons\HelloDjangopython manage.py startapp books D:\Documents\pythons\HelloDjango成功之后新建了一个APP名字为books。文件夹存放如下图然后我们把这个APP注册到工程里面打开HelloDjango下的settings.py文件路径【 D:\Documents\pythons\HelloDjango\HelloDjango\settings.py 】将books加入INSTALLED_APPS中最后如下INSTALLED_APPS(books,HelloDjango,django.contrib.admin,django.contrib.auth,django.contrib.contenttypes,django.contrib.sessions,django.contrib.messages,django.contrib.staticfiles,)增加存储结构打开books文件夹下面的models.py路径【 D:\Documents\pythons\HelloDjango\books\models.py 】输入内容如下fromdjango.dbimportmodels# Create your models here.classPublisher(models.Model):namemodels.CharField(max_length30);addressmodels.CharField(max_length50);citymodels.CharField(max_length60);state_provincemodels.CharField(max_length30);countrymodels.CharField(max_length50);websitemodels.URLField();classAuthor(models.Model):first_namemodels.CharField(max_length30);last_namemodels.CharField(max_length40);emailmodels.EmailField();classBook(models.Model):titlemodels.CharField(max_length100);authorsmodels.ManyToManyField(Author);publishermodels.ForeignKey(Publisher);publication_datemodels.DateField();这里的需要注意的是Book类的authors和publisher的定义。输入完毕之后我们验证一下是否输入有效D:\Documents\pythons\HelloDjangopython manage.py validate 0 errors found没有错误就开始生成SQL命令D:\Documents\pythons\HelloDjangopython manage.py sqlall booksBEGIN;CREATETABLEbooks_publisher(idintegerNOTNULLPRIMARYKEY,namevarchar(30)NOTNULL,addressvarchar(50)NOTNULL,cityvarchar(60)NOTNULL,state_provincevarchar(30)NOTNULL,countryvarchar(50)NOTNULL,websitevarchar(200)NOTNULL);CREATETABLEbooks_author(idintegerNOTNULLPRIMARYKEY,first_namevarchar(30)NOTNULL,last_namevarchar(40)NOTNULL,emailvarchar(75)NOTNULL);CREATETABLEbooks_book_authors(idintegerNOTNULLPRIMARYKEY,book_idintegerNOTNULL,author_idintegerNOTNULLREFERENCESbooks_author(id),UNIQUE(book_id,author_id));CREATETABLEbooks_book(idintegerNOTNULLPRIMARYKEY,titlevarchar(100)NOTNULL,publisher_idintegerNOTNULLREFERENCESbooks_publisher(id),publication_datedateNOTNULL);CREATEINDEXbooks_book_authors_36c249d7ONbooks_book_authors(book_id);CREATEINDEXbooks_book_authors_e969df21ONbooks_book_authors(author_id);CREATEINDEXbooks_book_81b79144ONbooks_book(publisher_id);COMMIT;D:\Documents\pythons\HelloDjango这里我们也没有显式的定义主键django会自动生成一个自增长的整数主键名字为id。由于book和author是多对多的关系django额外自动生成了一个对应关系表books_book_authors。不过这里感觉有点问题books_book_authors的book_id应该也有外键关联才对但是这里SQL没有体现出来。这里打印出SQL并没有真正的执行执行SQL需要继续输入命令D:\Documents\pythons\HelloDjangopython manage.py syncdb Creating tables ... Creating table books_publisher Creating table books_author Creating table books_book_authors Creating table books_book Creating table django_admin_log Creating table auth_permission Creating table auth_group_permissions Creating table auth_group Creating table auth_user_groups Creating table auth_user_user_permissions Creating table auth_user Creating table django_content_type Creating table django_session You just installed Djangos auth system, which means you dont have any superusers defined. Would you like to create one now? (yes/no):由于我们的工程默认启动了admin模块因此在第一次数据库写入时会提醒我们是否把管理员权限启动这里我们选择yes。输入用户名邮箱和密码。后续会提及它的使用。这里先把网址放出来http://127.0.0.1:8000/admin/。SQL执行完毕之后数据库表就建好了这里我们用软件打开看一下数据库操作简单的插入和查询打开CMD输入命令D:\Documents\pythons\HelloDjangopython manage.py shellfrombooks.modelsimport*p1Publisher(nameApress,address2855 Txx Axx,cityBerkeley,state_provinceCA,countryUSA,websitehttp://www.apress.com/);p1.save();p2Publisher(nameOReilly,address10 Fxx Sxx,cityCambridge,state_provinceMA,countryUSA,websitehttp://www.oreilly.com/);p2.save();publisher_listPublisher.objects.all();publisher_list[Publisher:Publisherobject,Publisher:Publisherobject]这里调用save方法会写入数据库。用工具看一下已经插入了这里查询数据时可以看到读取的数据打印到控制台上不好阅读这里我们通过增加**__unicode__方法来修复注意如果这里是python3.x版本__unicode__已经被废弃方法名称应该为__str__。修改后的models.py**classPublisher(models.Model):。。。。。。def__unicode__(self):returnuName:%s WebSite:%s%(self.name,self.website);classAuthor(models.Model):。。。。。。def__unicode__(self):returnufirst:%s last:%s%(self.first_name,self.last_name);classBook(models.Model):。。。。。。def__unicode__(self):returnutitle:%s%(self.title);修改好之后如果要看效果需要重启下shellexit()D:\Documents\pythons\HelloDjangopython manage.py shellfrombooks.modelsimport*publisher_listPublisher.objects.all();publisher_list[Publisher:Name:Apress WebSite:http://www.apress.com/,Publisher:Name:OReilly WebSite:http://www.oreilly.com/]条件查找参考网址https://docs.djangoproject.com/en/1.6/topics/db/queries/这里只笔记几个简单的精确查找Publisher.objects.filter(nameApress)[Publisher:Name:Apress WebSite:http://www.apress.com/]Publisher.objects.filter(countryU.S.A.,state_provinceCA)[]模糊查找在 name 和 contains 之间有双下划线。这里contains部分会被Django翻译成LIKE语句Publisher.objects.filter(name__containspress)[Publisher:Name:Apress WebSite:http://www.apress.com/]定位到单个对象注意这里如果返回数目多于1个或者没有返回均会报错Publisher.objects.get(nameApress)Publisher:Name:Apress WebSite:http://www.apress.com/排序与逆向排序:Publisher.objects.order_by(name)[Publisher:Name:Apress WebSite:http://www.apress.com/,Publisher:Name:OReilly WebSite:http://www.oreilly.com/]Publisher.objects.order_by(-name)[Publisher:Name:OReilly WebSite:http://www.oreilly.com/,Publisher:Name:Apress WebSite:http://www.apress.com/]复合查询Publisher.objects.filter(countryUSA).order_by(-name)[0]Publisher:Name:OReilly WebSite:http://www.oreilly.com/更新Publisher.objects.filter(countryUSA).update(countryU.S.A.)2删除Publisher.objects.filter(countryUSA).delete()Publisher.objects.all().delete()备注各种有意思的评注