环境: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