zoukankan      html  css  js  c++  java
  • django: db

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

    一,在 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 数据库的多对多关系操作十分方便。

  • 相关阅读:
    java设计模式之组合模式
    java设计模式之建造者
    设计模式之单例
    oracle 中update select 和连接字符串配合使用
    策略模式之使用场景
    javascript面向对象学习笔记——创建对象(转)
    grunt自动化工具
    【grunt整合版】30分钟学会使用grunt打包前端代码
    浅谈Hybrid技术的设计与实现
    WEB服务器、应用程序服务器、HTTP服务器区别(转)
  • 原文地址:https://www.cnblogs.com/exclm/p/3366153.html
Copyright © 2011-2022 走看看