1. 建立app

在自己的工程项目目录下输入:

python manage.py startapp myapp(你想建立的app名称)

建立一个叫myapp的app

这样,在你的工程项目目录下会出现一个叫myapp的目录

 

2. 创建Model

在app目录下进入models.py

输入类似下面的代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

class Publisher(models.Model):

    name = models.CharField(max_length=30)

    address = models.CharField(max_length=50)

    city = models.CharField(max_length=60)

    state_province = models.CharField(max_length=30)

    country = models.CharField(max_length=50)

    website = models.URLField()

class Author(models.Model):

    first_name = models.CharField(max_length=30)

    last_name = models.CharField(max_length=40)

    email = models.EmailField()

class Book(models.Model):

    title = models.CharField(max_length=100)

    authors = models.ManyToManyField(Author)

    publisher = models.ForeignKey(Publisher)

    publication_date = models.DateField()

 

上面的每个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 Bookdatabase 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 ...
Creating table books_publisher
Creating table books_author
Creating table books_book_authors
Creating table books_book
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)

这样的信息

 

值得注意的是,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.apress.com/')
>>> p1.save()

查看:

>>> publisher_list = Publisher.objects.all() 

>>> publisher_list

 

6. 额外问题:为model加入字符串表现形式

在每个model里加入:

1

2

def __unicode__(self):

    return self.name

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)

想直接获取单个对象?用get 方法!

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()方法:

1

2

3

>>> p = Publisher.objects.get(name='Apress')

>>> p.name = 'Apress Publishing'

>>> p.save()

——相当于

1

2

3

4

5

6

7

8

UPDATE books_publisher SET

    name 'Apress Publishing',

    address = '2855 Telegraph Ave.',

    city = 'Berkeley',

    state_province = 'CA',

    country = 'U.S.A.',

    website = 'http://www.apress.com'

WHERE id = 52;

!!所有的列都被更新了!这也太naive了吧!

 

2)用update() 方法才比较好:

Publisher.objects.filter(id=52).update(name='Apress Publishing')

——相当于

1

2

3

UPDATE books_publisher

SET name 'Apress Publishing'

WHERE id = 52;

 

可以对多行同时进行更新:

Publisher.objects.all().update(country='USA')

update()方法会返回一个整型数值,表示受影响的记录条数

 

10. (删除对象)delete:调用该对象的delete()方法即可:

p = Publisher.objects.get(name="O'Reilly")

p.delete()

一旦使用all()方法,所有数据将会被删除:

Publisher.objects.all().delete()

 

参考:http://www.djangobook.com/en/2.0/chapter05.html

http://djangobook.py3k.cn/2.0/chapter05/