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

时间:2023-02-01 07:06:59

首先,推荐一个网址: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/

在浏览器中运行,

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

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

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

刷新一下,结果如下:

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

7、再更改:

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

结果如下:

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

·8、遍历书的信息

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

效果如下:

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

·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'