django: db - many to many

时间:2023-03-09 22:46:29
django: db - many to many

本讲介绍数据库多对多关系,代码样例继前文使用。

一,在 blog/models.py 中创建对象:

# Many-To-Many Example : Authors vs Books
class Author(models.Model):
name = models.CharField(max_length=20) def __unicode__(self):
return self.name class Book(models.Model):
name = models.CharField(max_length=20)
authors = models.ManyToManyField(Author) def __unicode__(self):
return self.name

二,同步数据库:

[root@bogon csvt03]#  py manage.py syncdb
Creating tables ...
Creating table blog_author
Creating table blog_book_authors <--- 多对多映射表
Creating table blog_book
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)

三,Many-to-Many 数据的使用:

[root@bogon csvt03]#  ipython manage.py shell
In [1]: from blog.models import Author , Book In [2]: au1 = Author(name='Author-1') In [3]: au2 = Author(name='Author-2') In [4]: au3 = Author(name='Author-3') In [5]: au4 = Author(name='Author-4') In [6]: b1=Book(name='Book-1') In [7]: b1.save() <--- 必须先生成数据库实例才能添加多对多关系 In [8]: au1.save() <--- 必须先生成数据库实例才能添加多对多关系 In [9]: au2.save() <--- 必须先生成数据库实例才能添加多对多关系 In [10]: au3.save() <--- 必须先生成数据库实例才能添加多对多关系 In [11]: au4.save() <--- 必须先生成数据库实例才能添加多对多关系 In [12]: b1.authors.add(au1,au2) <--- 添加多对多关系 In [13]: b1.authors.all()
Out[13]: [<Author: Author-1>, <Author: Author-2>] In [14]: b1.authors.filter(name__exact='Author-2')
Out[14]: [<Author: Author-2>] In [15]: au1.book_set.all() <--- 多对多关系反向查询
Out[15]: [<Book: Book-1>] In [16]: au3.book_set.add(b1) <--- 多对多关系反向添加 In [17]: b1.authors.all()
Out[17]: [<Author: Author-1>, <Author: Author-2>, <Author: Author-3>] In [18]: au4.book_set.create(name='Book Newly Created') <--- 创建并添加多对多关系
Out[18]: <Book: Book Newly Created> In [19]: au4.book_set.all()
Out[19]: [<Book: Book Newly Created>] In [20]: au2.book_set.all()
Out[20]: [<Book: Book-1>] In [21]: au2.book_set.remove(b1) <--- 移除关系 In [22]: au2.book_set.all() In [23]:

可见,Django 数据库的多对多关系操作十分方便。