1. 建立app 在自己的工程项目目录下输入: python manage.py startapp myapp(你想建立的app名称) 建立一个叫myapp的app 这样,在你的工程项目目录下会出现一个叫myapp的目录 2. 创建Model 在app目录下进入models.py 输入类似下面的代码:
上面的每个class相当于一个新的table 例外是Many to Many 关系 (注:The exception to the one-class-per-database-table rule is the case ofmany-to-many relationships. In our example models, Book has aManyToManyField called authors. This designates that a book has one ormany authors, but the Book database table doesn’t get an authorscolumn. Rather, Django creates an additional table – a many-to-many “jointable” – that handles the mapping of books to authors.) django会自动给每个model配置一个名为id的primary key (Finally, note we haven’t explicitly defined a primary key in any of thesemodels. Unless you instruct it otherwise, Django automatically gives everymodel an auto-incrementing integer primary key field called id. Each Djangomodel is required to have a single-column primary key.) 3. 安装model 在最初的配置文件settings.py中找到 INSTALLED_APPS 加入自己的app名称,比如'myapp' 用下面的命令验证model的有效性: python manage.py validate 如果一切正常,你会看到 0errorsfound 消息。如果出错,请检查你输入的模型代码。 错误输出会给出非常有用的错误信息来帮助你修正你的模型。一旦你觉得你的模型可能有问题,运行 pythonmanage.pyvalidate 。 它可以帮助你捕获一些常见的模型定义错误。 4. (真正在DB创建我们设定好的table)create table: 在shell中输入 python manage.py sqlall myapp(步骤1中你创建的app名称) 然后你就可以看见各种SQL语句了,嗯,看上去不错。但是……坑爹的是“sqlall 命令并没有在数据库中真正创建数据表,只是把SQL语句段打印出来,这样你可以看到Django究竟会做些什么。” 所以说下面这个才是真正建表的语句: python manage.py syncdb 之后你应该能看到诸如: Creating tables ... 这样的信息 值得注意的是,syncdb 命令是同步你的模型到数据库的一个简单方法。 它会根据 INSTALLED_APPS 里设置的app来检查数据库, 如果表不存在,它就会创建它。 需要注意的是, syncdb 并 不能将模型的修改或删除同步到数据库;如果你修改或删除了一个模型,并想把它提交到数据库,syncdb并不会做出任何处理。 5. (插入一个新的对象) insert: >>> from books.models import Publisher >>> p1 = Publisher(name='Apress', address='2855 Telegraph Avenue', ... city='Berkeley', state_province='CA', country='U.S.A.', ... website='http://www./') >>> p1.save() 查看: >>> publisher_list = Publisher.objects.all() >>> publisher_list 6. 额外问题:为model加入字符串表现形式 在每个model里加入:
return 处写上你想要的字符串 7. (选择对象)select: Publisher.objects.all() ——相当于 select from Publisher.objects.filter(name='Apress') ——相当于 select from ... where name = 'Apress' Publisher.objects.filter(name__contains="press") ——相当于 select from ... where name LIKE '%press%'; 以上方法,返回的都是一个list (其实是query set)
Publisher.objects.get(name="Apress") 8. (对结果排序) order: Publisher.objects.order_by("name") ——相当于 select from ... ORDER BY name; 多项排序: Publisher.objects.order_by("state_province", "address") 逆向排序: Publisher.objects.order_by("-name") 连锁查询: Publisher.objects.filter(country="U.S.A.").order_by("-name") 9. (更新对象)update: 1)使用save()方法:
——相当于
!!所有的列都被更新了!这也太naive了吧! 2)用update() 方法才比较好: Publisher.objects.filter(id=52).update(name='Apress Publishing') ——相当于
可以对多行同时进行更新: Publisher.objects.all().update(country='USA') update()方法会返回一个整型数值,表示受影响的记录条数 10. (删除对象)delete: p = Publisher.objects.get(name="O'Reilly") p.delete() 一旦使用all()方法,所有数据将会被删除: Publisher.objects.all().delete() 参考:http://www./en/2.0/chapter05.html http://djangobook./2.0/chapter05/ |
|