django笔记-模型数据模板呈现过程记录(多对多关系)

环境:ubuntu+terminal(前面这几步是上次的重复,可略过)

1、建立工程和应用:

[email protected]:/home/uu# mkdir work

[email protected]:/home/uu# cd work

[email protected]:/home/uu/work# django-admin.py startproject csct06

[email protected]:/home/uu/work# cd csct06/

[email protected]:/home/uu/work/csct06# django-admin.py startapp blog

[email protected]:/home/uu/work/csct06# ls
blog  csct06  manage.py

2、完成基本设置:

[email protected]:/home/uu/work/csct06# vim csct06/settings.py 

INSTALLED_APPS = (
    ‘django.contrib.admin‘,
    ‘django.contrib.auth‘,
    ‘django.contrib.contenttypes‘,
    ‘django.contrib.sessions‘,
    ‘django.contrib.messages‘,
    ‘django.contrib.staticfiles‘,
    ‘blog‘,
)

DATABASES = {
    ‘default‘: {
        ‘ENGINE‘: ‘django.db.backends.sqlite3‘,
        ‘NAME‘: os.path.join(BASE_DIR, ‘db.sqlite3‘),
    }
}
[email protected]:/home/uu/work/csct06# vim blog/models.py 

from django.db import models
class Author(models.Model):
    name = models.CharField(max_length=30)

    def __unicode__(self):
        return self.name

class Book(models.Model):
    name = models.CharField(max_length=30)
    authors = models.ManyToManyField(Author)

    def __unicode__(self):
        return self.name

3、同步数据库:

[email protected]:/home/uu/work/csct06# ls
blog  csct06  manage.py
[email protected]:/home/uu/work/csct06# python manage.py syncdb
。。。。。
Creating tables ...
Creating table django_admin_log
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_groups
Creating table auth_user_user_permissions
Creating table auth_user
Creating table django_content_type
Creating table django_session
Creating table blog_author
Creating table blog_book_authors
Creating table blog_book

You just installed Django‘s auth system, which means you don‘t have any superusers defined.
Would you like to create one now? (yes/no): yes
Username (leave blank to use ‘root‘): uu
Email address: [email protected]
Password:
Password (again):
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)

绿色部分为生成的数据库,生成的数据文件为db.sqlite3:

[email protected]:/home/uu/work/csct06# ls
blog  csct06  db.sqlite3  manage.py

遇到了一个小问题,以前常用mysql的,

[email protected]:/home/uu/work/csct06# sqlite3 db.sqlite3
程序“sqlite3”尚未安装。 您可以使用以下命令安装:
apt-get install sqlite3

按照提示做就行了,

#apt-get install sqlite3

。。。

[email protected]:/home/uu/work/csct06# sqlite3 db.sqlite3
SQLite version 3.8.2 2013-12-06 14:53:30
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>
好了,可以操作数据库了。

4、操作数据库:

·1查看生成的数据库表:

sqlite> .tables
auth_group                  blog_author
auth_group_permissions      blog_book
auth_permission             blog_book_authors
auth_user                   django_admin_log
auth_user_groups            django_content_type
auth_user_user_permissions  django_session
sqlite> 

·2进入解释器,对数据进行整理

1)遇到一个小问题:

[email protected]:/home/uu/work/csct06# ipython manage.py shell
程序“ipython”尚未安装。 您可以使用以下命令安装:
apt-get install ipython

按照操作进行,

#apt-get install ipython

出故障了,

[email protected]:/home/uu/work/csct06# ipython manage.py shell
Usage: manage.py subcommand [options] [args]

Options:
  -v VERBOSITY, --verbosity=VERBOSITY
                        Verbosity level; 0=minimal output, 1=normal output,
                        2=verbose output, 3=very verbose output
  --settings=SETTINGS   The Python path to a settings module, e.g.
                        "myproject.settings.main". If this isn‘t provided, the
                        DJANGO_SETTINGS_MODULE environment variable will be
                        used.
  --pythonpath=PYTHONPATH
                        A directory to add to the Python path, e.g.
                        "/home/djangoprojects/myproject".
  --traceback           Raise on exception
  --version             show program‘s version number and exit
  -h, --help            show this help message and exit

Type ‘manage.py help <subcommand>‘ for help on a specific subcommand.

Available subcommands:

[auth]
    changepassword
    createsuperuser

[django]
    check
    cleanup
    compilemessages
    createcachetable
    dbshell
    diffsettings
    dumpdata
    flush
    inspectdb
    loaddata
    makemessages
    runfcgi
    shell
    sql
    sqlall
    sqlclear
    sqlcustom
    sqldropindexes
    sqlflush
    sqlindexes
    sqlinitialdata
    sqlsequencereset
    startapp
    startproject
    syncdb
    test
    testserver
    validate

[sessions]
    clearsessions

[staticfiles]
    collectstatic
    findstatic
    runserver
[email protected]:/home/uu/work/csct06# ls
blog  csct06  db.sqlite3  manage.py
[email protected]:/home/uu/work/csct06# ip
ip                          ipod-read-sysinfo-extended
ip6tables                   ipod-time-sync
ip6tables-apply             ippfind
ip6tables-restore           ipptool
ip6tables-save              iproxy
ipcluster                   iptables
ipcmk                       iptables-apply
ipcontroller                iptables-restore
ipcrm                       iptables-save
ipcs                        iptables-xml
ipengine                    iptunnel
iplogger                    ipython
ipmaddr                     ipython2.7
[email protected]:/home/uu/work/csct06# ipython2.7 manage.py shell
/usr/lib/python2.7/dist-packages/IPython/frontend.py:30: UserWarning: The top-level `frontend` package has been deprecated. All its subpackages have been moved to the top `IPython` level.
  warn("The top-level `frontend` package has been deprecated. "
---------------------------------------------------------------------------
MultipleInstanceError                     Traceback (most recent call last)
/usr/lib/python2.7/dist-packages/IPython/utils/py3compat.pyc in execfile(fname, *where)
    202             else:
    203                 filename = fname
--> 204             __builtin__.execfile(filename, *where)

/home/uu/work/csct06/manage.py in <module>()
      8     from django.core.management import execute_from_command_line
      9
---> 10     execute_from_command_line(sys.argv)

/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.pyc in execute_from_command_line(argv)
    397     """
    398     utility = ManagementUtility(argv)
--> 399     utility.execute()

/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.pyc in execute(self)
    390             sys.stdout.write(self.main_help_text() + ‘\n‘)
    391         else:
--> 392             self.fetch_command(subcommand).run_from_argv(self.argv)
    393
    394 def execute_from_command_line(argv=None):

/usr/local/lib/python2.7/dist-packages/django/core/management/base.pyc in run_from_argv(self, argv)
    240         handle_default_options(options)
    241         try:
--> 242             self.execute(*args, **options.__dict__)
    243         except Exception as e:
    244             if options.traceback or not isinstance(e, CommandError):

/usr/local/lib/python2.7/dist-packages/django/core/management/base.pyc in execute(self, *args, **options)
    283             if self.requires_model_validation and not options.get(‘skip_validation‘):
    284                 self.validate()
--> 285             output = self.handle(*args, **options)
    286             if output:
    287                 if self.output_transaction:

/usr/local/lib/python2.7/dist-packages/django/core/management/base.pyc in handle(self, *args, **options)
    413         if args:
    414             raise CommandError("Command doesn‘t accept any arguments")
--> 415         return self.handle_noargs(**options)
    416
    417     def handle_noargs(self, **options):

/usr/local/lib/python2.7/dist-packages/django/core/management/commands/shell.pyc in handle_noargs(self, **options)
     79                 raise ImportError
     80
---> 81             self.run_shell(shell=interface)
     82         except ImportError:
     83             import code

/usr/local/lib/python2.7/dist-packages/django/core/management/commands/shell.pyc in run_shell(self, shell)
     59         for shell in available_shells:
     60             try:
---> 61                 return getattr(self, shell)()
     62             except ImportError:
     63                 pass

/usr/local/lib/python2.7/dist-packages/django/core/management/commands/shell.pyc in ipython(self)
     42         for ip in (self._ipython, self._ipython_pre_100, self._ipython_pre_011):
     43             try:
---> 44                 ip()
     45             except ImportError:
     46                 pass

/usr/local/lib/python2.7/dist-packages/django/core/management/commands/shell.pyc in _ipython(self)
     36         """Start IPython >= 1.0"""
     37         from IPython import start_ipython
---> 38         start_ipython(argv=[])
     39
     40     def ipython(self):

/usr/lib/python2.7/dist-packages/IPython/__init__.pyc in start_ipython(argv, **kwargs)
    116     """
    117     from IPython.terminal.ipapp import launch_new_instance
--> 118     return launch_new_instance(argv=argv, **kwargs)
    119
    120 def start_kernel(argv=None, **kwargs):

/usr/lib/python2.7/dist-packages/IPython/config/application.pyc in launch_instance(cls, argv, **kwargs)
    542         """
    543         try:
--> 544             app = cls.instance(**kwargs)
    545             app.initialize(argv)
    546             app.start()

/usr/lib/python2.7/dist-packages/IPython/config/configurable.pyc in instance(cls, *args, **kwargs)
    358             raise MultipleInstanceError(
    359                 ‘Multiple incompatible subclass instances of ‘
--> 360                 ‘%s are being created.‘ % cls.__name__
    361             )
    362 

MultipleInstanceError: Multiple incompatible subclass instances of TerminalIPythonApp are being created.

命令出错了,因该是以下命令:

# python manage.py shell

创建四个作者:

[email protected]:/home/uu/work/csct06# python manage.py shell
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
。。。。
下面开始执行操作:
In [1]: from blog.models import Author,Book

In [2]: Author.objects.create(name=‘Tom1‘)
Out[2]: <Author: Tom1>

In [3]: Author.objects.create(name=‘Tom2‘)
Out[3]: <Author: Tom2>

In [4]: Author.objects.create(name=‘Bob1‘)
Out[4]: <Author: Bob1>

In [5]: Author.objects.create(name=‘Bob2‘)
Out[5]: <Author: Bob2>
In [8]: auhtors = Author.objects.all()   这里出错了
In [9]: authors
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-9-07dd264ecf4d> in <module>()
----> 1 authors
NameError: name ‘authors‘ is not defined
按照下面的步骤走,可以解决直接查询所有作者:
In [11]: Author.objects.all()
Out[11]: [<Author: Tom1>, <Author: Tom2>, <Author: Bob1>, <Author: Bob2>]
通过赋值查询所有结果:
In [12]: author = Author.objects.all()
In [13]: author
Out[13]: [<Author: Tom1>, <Author: Tom2>, <Author: Bob1>, <Author: Bob2>]
In [14]: b1 = Book()       获取b1对象
In [15]: b1.name = ‘Java‘     添加第一本书:Java
In [16]: b1.save()                 用sava方法保存
为书Java添加作者:
In [20]: tom1 = Author.objects.get(name_exact=‘Tom1‘)
---------------------------------------------------------------------------
FieldError                                Traceback (most recent call last)
。。。
  name_exact方法出错,处理:
In [21]: tom1 = Author.objects.get(name=‘Tom1‘)In [22]: tom1Out[22]: <Author: Tom1>添加第一个作者:In [23]: b1.authors.add(tom1)添加成功:In [24]: b1.authors.all()Out[24]: [<Author: Tom1>]

添加第二个作者:In [26]: b1.authors.add(author[2])In [27]: b1.authors.all()Out[27]: [<Author: Tom1>, <Author: Bob1>]第三个作者,注意一下下标:In [28]: b1.authors.add(author[1])In [29]: b1.authors.all()Out[29]: [<Author: Tom1>, <Author: Tom2>, <Author: Bob1>] 删除一个作者,调用remove方法:In [30]: b1.authors.remove(tom1)用all方法进行全部查询:In [31]: b1.authors.all()Out[31]: [<Author: Tom2>, <Author: Bob1>]用filter方法进行局部查询:In [31]: b1.authors.all()Out[31]: [<Author: Tom2>, <Author: Bob1>]这里已经删除了Tom1这个作者,所以查询不到:In [32]: b1.authors.filter(name=‘Tom1‘)Out[32]: []

In [33]: b1.authors.filter(name=‘Tom2‘)Out[33]: [<Author: Tom2>]
In [34]: tom1                  tom1对象前面已经获取了
Out[34]: <Author: Tom1>

In [35]: tom1.book_set.all()    set是一个集合,也可以看成一个对象
Out[35]: []

In [36]: tom1.book_set.add(b1)    同样用add方法为作者添加一本书,就是前面的书Java

In [40]: tom1.book_set.create(name="python")  添加第二本书Out[40]: <Book: python>

In [41]: tom1.book_set.all()                   共为tom1添加了两本书Out[41]: [<Book: Java>, <Book: python>]

In [42]: book = Book.objects.all()    查看书的集合In [43]: bookOut[43]: [<Book: Java>, <Book: python>]

In [44]: tom1.book_set.remove(book[0])   移除一本书

In [45]: tom1.book_set.all()Out[45]: [<Book: python>]

In [46]: 

各种模块学习大全:

http://blog.csdn.net/lcyangcss/article/details/7249961

时间: 2024-10-10 18:41:46

django笔记-模型数据模板呈现过程记录(多对多关系)的相关文章

django 学习-11 Django模型数据模板呈现

1.for author in Author.objects.all(): for book in author.book_set.all(): print   book 2.vim blog/views.py from blog.models  import Author,Book from  django.shortcuts   import  render_to_response def show_author(req): authors = Author.objects.all() re

Django 笔记 模型数据的读取

一开始我是根据 Django 1.8.2开发文档 http://python.usyiyi.cn/django/index.html http://python.usyiyi.cn/django/ref/contrib/admin/index.html 进行实验,后来有读者说旧的教程坑比较多 所以我现在以官方文档 https://docs.djangoproject.com/en/dev/topics/db/models/ 为主,进行实验 建立数据模型 Model.py class Person

Django 批量插入数据、自定义分页器、多表关系的建立及Form组件(待更新。。。)

目  录 django批量出入数据 自定义分页器 创建多对多表关系的建立 form组件 form组件钩子函数 一.django批量出入数据 视图函数: from app01 import models # 向表中插入1000条数据 def index(request): # 方式1: # for i in range(1000): # models.Book.objects.create(title='第%s本书'%i) # book_Queryset = models.Book.objects

Django笔记-模型(二)

新建project步骤省略,具体可参照http://5007260.blog.51cto.com/4997260/1310954 1.基础篇 cd /app/shenpi python manage.py startapp #data 模型需要建一个独立的app python manage.py validate #检测model.py是否存在语法错误 python manage.py sqlall data #(存放model.py app名字) python manage.py syncdb

配置ODBC DSN数据源,导出数据库数据到Excel过程记录

一.前言 工作中我们可能遇到这样的需要:查询数据库中的信息,并将结果导出到Excel文件.这本来没什么,但数据量比较大时,用PLSQL.toad导出Excel会出现内存不足等情况,使用odbc+Microsoft query + Excel导出提数结果能在一定程度上避免这些问题. 环境:个人电脑8G内存,导出130W条记录毫无压力. 二.下载.安装Oracle Database Client Windows默认没有按照Oracle的ODBC驱动,需要手动安装,Oracle Database Cl

Django ORM模型的一点体会

作者:Vamei 出处:http://www.cnblogs.com/vamei 严禁转载. 使用Python的Django模型的话,一般都会用它自带的ORM(Object-relational mapping)模型.这个ORM模型的设计比较简单,学起来不会特别花时间.不过,Django的ORM模型有自己的一套语法,有时候会觉得别扭.这里聊一下我自己的体会. 模型设计 这一部分算处理得比较好的部分.Django的数据模型的建立过程很简单,就是继承django.db.models中的Model类,

SpringMVC:学习笔记(4)——处理模型数据

SpringMVC-处理模型数据 说明 SpringMVC 提供了以下几种途径输出模型数据: – ModelAndView: 处理方法返回值类型为 ModelAndView时, 方法体即可通过该对象添加模型数据 – Map及Model:入参为org.springframework.ui.Model.org.springframework.ui.ModelMap 或 Java.uti.Map 时,处理方法返回时,Map中的数据会自动添加到模型中. – @SessionAttributes: 将模型

通过json序列化方式在django下传递模型数据

由于操作的原因,往往需要页面通过ajax后台加载一些数据,但是在django下,数据往往是通过models获得实例得到的,而传统的json格式只支持dict和list,创建的模型类是不能被序列化的.因此需要先导入from django.core import serializers,采用serializers.serialize("json",queryset)的方法序列化实例.在网页脚本中需要先解读json文件,再获取fields对应的各个实例属性.javascript中通过eval

flask快速入门笔记四_模板:分离数据与视图

首先声明:内容大部分来自huizhiwang,只是单纯记笔记. 1 模板引擎 在Flask中,视图函数的返回值为响应的正文被送往前端浏览器.毫无疑问,一个实用 的视图函数需要在服务端根据请求的不同动态构造这个内容.然而手工拼接一段冗长 的HTML串是乏味而且相当容易出错. 这正是模板引擎发挥威力的地方,只需要将模板和数据送入模板引擎,我们就告 别了那些那些拼接.转义之类的琐碎之事,轻松得到一个渲染后的字符串: