[Dynamic Language] Python Django: 模型使用
Django 模型
//创建App应用程序
python manage.py startapp books
//建立模型
代码
1 from django.db import models
2
3 # Create your models here.
4
5 class Publisher(models.Model):
6 name = models.CharField(max_length=30)
7 address = models.CharField(max_length=50)
8 city = models.CharField(max_length=60)
9 state_province = models.CharField(max_length=30)
10 country = models.CharField(max_length=50)
11 website = models.URLField()
12
13 class Author(models.Model):
14 first_name = models.CharField(max_length=100)
15 last_name = models.CharField(max_length=40)
16 email = models.EmailField()
17
18 class Book(models.Model):
19 title = models.CharField(max_length=100)
20 authors = models.ManyToManyField(Author)
21 publisher = models.ForeignKey(Publisher)
22 publication_date = models.DateField()
模型安装
修改 settings.py 配置信息
代码
70 MIDDLEWARE_CLASSES = (
71 # 'django.middleware.common.CommonMiddleware',
72 # 'django.contrib.sessions.middleware.SessionMiddleware',
73 # 'django.middleware.csrf.CsrfViewMiddleware',
74 # 'django.contrib.auth.middleware.AuthenticationMiddleware',
75 # 'django.contrib.messages.middleware.MessageMiddleware',
76 )
88 INSTALLED_APPS = (
89 # 'django.contrib.auth',
90 # 'django.contrib.contenttypes',
91 # 'django.contrib.sessions',
92 'django.contrib.sites',
93 # 'django.contrib.messages',
94 'mysite.books',
95 # Uncomment the next line to enable the admin:
96 # 'django.contrib.admin',
97 )
//验证模型的有效性
abeen@localhost:~/django_test/mysite$ python manage.py validate
0 errors found
//打印输出sql语句
代码
abeen@localhost:~/django_test/mysite$ python manage.py sqlall books
BEGIN;
CREATE TABLE `books_publisher` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`name` varchar(30) NOT NULL,
`address` varchar(50) NOT NULL,
`city` varchar(60) NOT NULL,
`state_province` varchar(30) NOT NULL,
`country` varchar(50) NOT NULL,
`website` varchar(200) NOT NULL
);
CREATE TABLE `books_author` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`first_name` varchar(100) NOT NULL,
`last_name` varchar(40) NOT NULL,
`email` varchar(75) NOT NULL
);
CREATE TABLE `books_book_authors` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`book_id` integer NOT NULL,
`author_id` integer NOT NULL,
UNIQUE (`book_id`, `author_id`)
);
ALTER TABLE `books_book_authors` ADD CONSTRAINT `author_id_refs_id_9e7e386`
FOREIGN KEY (`author_id`) REFERENCES `books_author` (`
CREATE TABLE `books_book` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`title` varchar(100) NOT NULL,
`publisher_id` integer NOT NULL,
`publication_date` date NOT NULL
);
ALTER TABLE `books_book` ADD CONSTRAINT `publisher_id_refs_id_c5b274bb`
FOREIGN KEY (`publisher_id`) REFERENCES `books_publisher`
ALTER TABLE `books_book_authors` ADD CONSTRAINT `book_id_refs_id_cfbcf262`
FOREIGN KEY (`book_id`) REFERENCES `books_book` (`id`);
CREATE INDEX `books_book_22dd9c39` ON `books_book` (`publisher_id`);
COMMIT;
//同步模型到数据库
代码
abeen@localhost:~/django_test/mysite$ python manage.py syncdb
Creating table books_publisher
Creating table books_author
Creating table books_book_authors
Creating table books_book
Installing index for books.Book_authors model
Installing index for books.Book model
No fixtures found.
基本数据访问
代码
In [1]: from books.models import Publisher //导入
//创建对象
In [2]: p = Publisher(name='Apress',address='2855,Telegraph Avenue',city='Berkeley',
state_province='CA',country='USA',website='http://www.jinry.com')
//存入数据库
In [3]: p.save()
In [4]: p2 = Publisher(name='Apress',address='2855,Telegraph Avenue',city='Berkeley',
state_province='CA',country='USA',website='http://www.jinry.com')
In [5]: p2.save()
//取信息
In [6]: publisher_list = Publisher.objects.all()
In [7]: publisher_list
Out[7]: [<Publisher: Publisher object>, <Publisher: Publisher object>]
In [8]: type(publisher_list)
Out[8]: <class 'django.db.models.query.QuerySet'>
//创建并直接存入数据库
In [9]: p2 = Publisher.objects.create(name='Apress',address='2855,Telegraph Avenue',
city='Berkeley',state_province='CA',country='USA',website='http://www.jinry.com')
选择对象集
In [9]: publisher_list = Publisher.objects.all()//取全部
In [10]: publisher_list
Out[10]: [<Publisher: abeen>, <Publisher: shanshan>, <Publisher: Apress>]
数据过滤
代码
In [16]: publisher = Publisher.objects.filter(name="abeen")
In [17]: publisher
Out[17]: [<Publisher: abeen>]//sql and
In [21]: publishers = Publisher.objects.filter(name="abeen", city="hai dian")
In [22]: publishers
Out[22]: [<Publisher: abeen>]
In [23]: publishers = Publisher.objects.filter(name__contains="a") //包含关系
In [25]: publishers
Out[25]: [<Publisher: abeen>, <Publisher: shanshan>]
获取单个对象
In [27]: p = Publisher.objects.get(name="abeen")
In [28]: p
Out[28]: <Publisher: abeen>
注意get在取不到结果或取到多个结果时,会报DoesNotExist错误,程序要自己处理。如:
代码
In [30]: try:
....: p = Publisher.objects.get(name="abeen1")
....: except Publisher.DoesNotExist:
....: print "abeen1 is not in "
....: else:
....: p
....:
....:
abeen1 is not in
数据排序
数据排序
In [39]: Publisher.objects.all()
Out[39]: [<Publisher: abeen>, <Publisher: shanshan>, <Publisher: Apress>,
<Publisher: binbin>, <Publisher: qiqi>, <Publisher: lanlan>]
In [40]: Publisher.objects.order_by("name") //按name排序
Out[40]: [<Publisher: abeen>, <Publisher: Apress>, <Publisher: binbin>,
<Publisher: lanlan>, <Publisher: qiqi>, <Publisher: shanshan>]
In [41]: Publisher.objects.order_by("name", "city") //多字段排序
Out[41]: [<Publisher: abeen>, <Publisher: Apress>, <Publisher: binbin>,
<Publisher: lanlan>, <Publisher: qiqi>, <Publisher: shanshan>]
In [42]: Publisher.objects.order_by("-name") //逆向排序,在前面加一个减号 - 前缀
Out[42]: [<Publisher: shanshan>, <Publisher: qiqi>, <Publisher: lanlan>,
<Publisher: binbin>, <Publisher: Apress>, <Publisher: abeen>]
如果感觉每次查询都要写order_by啰嗦的话,可以用Meta来设置模型默认的排序字段
代码
5 class Publisher(models.Model):
6 name = models.CharField(max_length=30)
7 address = models.CharField(max_length=50)
8 city = models.CharField(max_length=60)
9 state_province = models.CharField(max_length=30)
10 country = models.CharField(max_length=50)
11 website = models.URLField()
12
13 def __unicode__(self):
14 return self.name
15
16 class Meta:
17 ordering = ['name']
查询看一下结果默认按name排序了
代码
In [1]: from books.models import Publisher
In [2]: P = Publisher
In [3]: P.objects.all()
Out[3]: [<Publisher: abeen>, <Publisher: Apress>, <Publisher: binbin>,
<Publisher: lanlan>, <Publisher: qiqi>, <Publisher: shanshan>]
注意可以在任意一个模型类中使用 Meta 类,来设置一些与特定模型相关的选项。
(参考与特定模型相关选项 http://djangobook.py3k.cn/appendixB/)
连锁查询
In [5]: p = Publisher.objects.filter(name__contains="a").order_by("name")
In [6]: p
Out[6]: [<Publisher: abeen>, <Publisher: lanlan>, <Publisher: shanshan>]
限制返回的数据
代码
In [7]: Publisher.objects.all()[1] //按索引号取
Out[7]: <Publisher: Apress>
In [8]: Publisher.objects.all()[0:2] //按范围取
Out[8]: [<Publisher: abeen>, <Publisher: Apress>]
In [9]: Publisher.objects.all().order_by("-name")[0:2] //不支持负索引,可以后逆排实现效果
Out[9]: [<Publisher: shanshan>, <Publisher: qiqi>]
更新多个对象
In [11]: p = Publisher.objects.get(name="abeen")
In [12]: p
Out[12]: <Publisher: abeen>
In [13]: p.name="new abeen"
In [14]: p.save() //将所有字段都更新,即使只修改某个字段
先看一下数据库数据
代码
mysql> select * from books_publisher;
+----+-----------+-----------------------+------------+----------------+---------+----------------------+
| id | name | address | city | state_province | country | website |
+----+-----------+-----------------------+------------+----------------+---------+----------------------+
| 1 | new abeen | 2855,Telegraph Avenue | hai dian | CA | USA | http://www.jinry.com |
| 2 | shanshan | 2855,Telegraph Avenue | feng tai | CA | USA | http://www.jinry.com |
| 3 | Apress | 2855,Telegraph Avenue | Berkeley | CA | USA | http://www.jinry.com |
| 4 | binbin | | shou guang | | | |
| 5 | qiqi | | shou guang | | | |
| 6 | lanlan | | shou guang | | | |
+----+-----------+-----------------------+------------+----------------+---------+----------------------+
In [16]: Publisher.objects.filter(id="1").update(name="abeen")
Out[16]: 1L
In [17]: Publisher.objects.all().update(website="http://www.jinry.com")
Out[17]: 6L
数据已修改
代码
mysql> select * from books_publisher;
+----+----------+-----------------------+------------+----------------+---------+----------------------+
| id | name | address | city | state_province | country | website |
+----+----------+-----------------------+------------+----------------+---------+----------------------+
| 1 | abeen | 2855,Telegraph Avenue | hai dian | CA | USA | http://www.jinry.com |
| 2 | shanshan | 2855,Telegraph Avenue | feng tai | CA | USA | http://www.jinry.com |
| 3 | Apress | 2855,Telegraph Avenue | Berkeley | CA | USA | http://www.jinry.com |
| 4 | binbin | | shou guang | | | http://www.jinry.com |
| 5 | qiqi | | shou guang | | | http://www.jinry.com |
| 6 | lanlan | | shou guang | | | http://www.jinry.com |
+----+----------+-----------------------+------------+----------------+---------+----------------------+
删除对象
In [18]: Publisher.objects.filter(name="lanlan").delete()
In [19]: p = Publisher.objects.get(name="binbin")
In [20]: p.delete()
//删除表数据时要注意,显示调用all(),否则会出如下错误
代码
In [21]: Publisher.objects.delete()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
/home/abeen/django_test/mysite/<ipython console> in <module>()
AttributeError: 'Manager' object has no attribute 'delete'
//删除表内全部数据
In [22]: Publisher.objects.all().delete()