首先,推荐一个网址:http://www.tuicool.com/articles/BfqYz2F,因为这里的比我的要有条理,更有利于各位的理解。

以下仅为为个人一次不完整的笔记:

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

(PS:这个没有做完,有时间了我重新理一遍,做个调查问卷的例子)

1、建立工程和应用:

root@pc:/home/uu# mkdir work     建立一个文件夹,用于存放工程

root@pc:/home/uu# cd work

root@pc:/home/uu/work# django-admin.py startproject csct06     建立一个工程csct06

root@pc:/home/uu/work# cd csct06/

root@pc:/home/uu/work/csct06# django-admin.py startapp blog     建立一个应用

root@pc:/home/uu/work/csct06# ls
blog csct06 manage.py

2、完成基本设置:

root@pc:/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', 这里如果用MySQL或类似数据库,只需要更改这里的相关参数就行了
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 参数有6个:'ENGINE'为数据库的类型,'NAME'为使用的数据库名,'USER'为管理员名字
} ‘HOST'一般为localhost,’PORT'为数据库的端口,'PASSWORD'为数据库密码
}
root@pc:/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、同步数据库:

root@pc:/home/uu/work/csct06# ls
blog csct06 manage.py
root@pc:/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: uu@qw.com
Password:
Password (again):
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)

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

root@pc:/home/uu/work/csct06# ls
blog csct06 db.sqlite3 manage.py

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

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

按照提示做就行了,

#apt-get install sqlite3

。。。

root@pc:/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)遇到一个小问题:

root@pc:/home/uu/work/csct06# ipython manage.py shell
程序“ipython”尚未安装。 您可以使用以下命令安装:
apt-get install ipython 按照操作进行, #apt-get install ipython 出故障了,
root@pc:/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
root@pc:/home/uu/work/csct06# ls
blog csct06 db.sqlite3 manage.py
root@pc:/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
root@pc:/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

创建四个作者:

root@pc:/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') 用create方法插入数据
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]: tom1
Out[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]: book
Out[43]: [<Book: Java>, <Book: python>] In [44]: tom1.book_set.remove(book[0]) 移除一本书 In [45]: tom1.book_set.all()
Out[45]: [<Book: python>]

5、继续上午的编辑,首先,查看上面做的结果

In [2]: from blog.models import Author,Book 首先导入两个对象作者和书

In [4]: authors = Author.objects.all()     赋值

In [5]: authors                       间接查询
Out[5]: [<Author: Tom1>, <Author: Tom2>, <Author: Bob1>, <Author: Bob2>] In [6]: a1 = authors[0] 特定查询第一个作者的信息
In [7]: a1.book_set
Out[7]: <django.db.models.fields.related.ManyRelatedManager at 0x7f7f46e53c10>
In [9]: a1.book_set.all()[0] 详细查看作者a1出版的书的信息
Out[9]: <Book: python> In [11]: for author in Author.objects.all(): 这里通过一个复杂的结构完成类似功能
   ....:     for book in author.book_set.all():
   ....:         print book
   ....:         
python
Java
Java
各种模块学习大全:

6、如何在web中展现

·1、首先,在blog.views.py里将数据库的内容渲染到html中

blog.views.py

#coding=utf-8
from django.shortcuts import render,render_to_response from blog.models import Author,Book 首先导入数据库里的对象 def show_author(req):
authors = Author.objects.all() 遍历作者信息
return render_to_response('show_author.html',{'authors':authors}) 将作者信息渲染到模板文件中

·2、然后,在应用blog目录下创建templates用来保存html

root@pc:/home/uu/work/csct06/blog# mkdir templates 
·3、其次,在templates里编辑一个show_author.html,

#vim  /blog/templates/show_author.html

先输入变量名,看能否运行:

{{authors}}

保存

·4、设置urls.py,添加映射

url(r'^blog/show_author/$','blog.views.show_author'), 保存推出:wq
·5、运行开发服务器

root@pc:/home/uu/work/csct06# python manage.py runserver
......
Django version 1.6.5, using settings 'csct06.settings'
Starting development server at http://127.0.0.1:8000/

在浏览器中运行,

·6、初步成功,接下来进一步完善

{%for author in authors%}
<li>{{author}}</li>
{%endfor%} 注意括号哪里是单括号,哪里是双括号

刷新一下,结果如下:

7、再更改:

{%for author in authors%}
<h1>{{author.name}}</h1>
{%endfor%}

结果如下:

·8、遍历书的信息

{%for author in authors%}
<div>
<h1>{{author.name}}</h1> 这里小结一下:变量用双括号:{{变量}}
{%for book in author.book_set.all%} for循环这里用但括号,且要加上%
<li> {{book}}</li>
{%endfor%}
</div>
{%endfor%}

效果如下:

·9、在解释器里继续操作

In [13]: tom1 = Author.objects.filter(name='Tom1')
In [14]: tom1
Out[14]: [<Author: Tom1>]http://blog.csdn.net/lcyangcss/article/details/7249961
下面这里出错了,还未解决,整理中。。。。。。
In [22]: tom1.book_set.create(name='django')
。。。。 AttributeError: 'QuerySet' object has no attribute 'book_set' In [23]: tom1.book_set.create(name="django")
。。。。 AttributeError: 'QuerySet' object has no attribute 'book_set'

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

  1. django ORM模型表的一对多、多对多关系、万能双下划线查询

    一.外键使用 在 MySQL 中,如果使用InnoDB引擎,则支持外键约束.(另一种常用的MyIsam引擎不支持外键) 定义外键的语法为fieldname=models.ForeignKey(to_c ...

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

    1.for author in Author.objects.all(): for book in author.book_set.all(): print   book 2.vim blog/vie ...

  3. Django笔记 —— 模型

    最近在学习Django,打算玩玩网页后台方面的东西,因为一直很好奇但却没怎么接触过.Django对我来说是一个全新的内容,思路想来也是全新的,或许并不能写得很明白,所以大家就凑合着看吧- 本篇笔记(其 ...

  4. Django笔记--模型

    ORM是"对象-关系-映射"的简称,在Django当中,ORM就是模型类的管理器对象.操作顺序是先定义模型类,再定义模型类管理器,然后在模型类中实例化一个模型类管理器的对象,作为模 ...

  5. Django入门--模型系统(二):常用查询及表关系的实现

    1.常用查询 模型类上的管理器: ** 模型类.objects ** (1)常用一般查询 rs = Student.objects.all() # 查询所有记录,返回Queryset print(rs ...

  6. SSAS中事实表中的数据如果因为一对多或多对多关系复制了多份,在维度上聚合的时候还是只算一份

    SSAS事实表中的数据,有时候会因为一对多或多对多关系发生复制变成多份,如下图所示: 图1 我们可以从上面图片中看到,在这个例子中,有三个事实表Fact_People_Money(此表用字段Money ...

  7. Django笔记 —— 模型高级进阶

    最近在学习Django,打算玩玩网页后台方面的东西,因为一直很好奇但却没怎么接触过.Django对我来说是一个全新的内容,思路想来也是全新的,或许并不能写得很明白,所以大家就凑合着看吧- 本篇笔记(其 ...

  8. Django笔记&教程 3-2 模板语法介绍

    Django 自学笔记兼学习教程第3章第2节--模板语法介绍 点击查看教程总目录 参考:https://docs.djangoproject.com/en/2.2/topics/templates/# ...

  9. Django笔记&教程 3-1 模板(Template)基础

    Django 自学笔记兼学习教程第3章第1节--模板(Template)基础 点击查看教程总目录 1 介绍 模板文件:让Django能够自动生成html代码 作为一个web框架,Django需要需要在 ...

随机推荐

  1. 【BZOJ 3527】【ZJOI 2014】力

    代换一下变成多项式卷积,这里是的答案是两个卷积相减,FFT求一下两个卷积就可以啦 详细的题解:http://www.cnblogs.com/iwtwiioi/p/4126284.html #inclu ...

  2. 【BZOJ 3735】苹果树 树上莫队(树分块+离线莫队+鬼畜的压行)

    2016-05-09 UPD:学习了新的DFS序列分块,然后发现这个东西是战术核导弹?反正比下面的树分块不知道要快到哪里去了 #include<cmath> #include<cst ...

  3. 概率 高消light oj 1151

    t个样例 n个楼梯或蛇; a b 刚好走到a会到b; 问走到100期望; dp[i]   i到100的期望 这一点没奇怪的东西 dp[i]=1/6(dp[i+1]+dp[i+2]..+6); 有   ...

  4. url中#号的作用

    url中#号的作用就是本页面位置跳转 比如这个url地址:http://www.aaaaa.com/index.html?ad=34&m=c#red red就是index.html页面的依哥位 ...

  5. block的使用

    转载自:http://mobile.51cto.com/hot-403897.htm 一.概述 Block是C级别的语法和运行时特性.Block比较类似C函数,但是Block比之C函数,其灵活性体现在 ...

  6. Mysql实现行列转换

    前言: 最近又玩起了sql语句,想着想着便给自己出了一道题目:“行列转换”.起初瞎折腾了不少时间也上网参考了一些博文,不过大多数是采用oracle数据库当中的一些便捷函数进行处理,比如”pivot”. ...

  7. an important difference between while and foreach on Perl

    while (<STDIN>) { } # will read from standard input one line at a time foreach (<STDIN>) ...

  8. AfNetworking 3.0源码解读

    做ios开发,AFNetworking 这个网络框架肯定都非常熟悉,也许我们平时只使用了它的部分功能,而且我们对它的实现原理并不是很清楚,就好像总是有一团迷雾在眼前一样. 接下来我们就非常详细的来读一 ...

  9. python 内建类型

    ''' 数值 numbers 字符串 strings 列表 lists 字典 dictionaries 元组 tuples 文件 files 集合 sets ''' 1.1 序列的操作 所有序列类型都 ...

  10. Python 小细节备忘

    1. 多行字符串可以通过三个连续的单引号 (”’) 或是双引号 (“”") 来进行标示 >>> a='''a bc def ''' >>> print a ...