Environment: Ubuntu+terminal (The previous steps are the last repetition, can be skipped)
1, the establishment of engineering and application:
[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# lsblog csct06 manage.py
2. Complete the basic setup:
[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 Modelsclass Author (models. Model): name = models. Charfield (max_length=30) def __unicode__ (self): return Self.nameclass book (models. Model): name = models. Charfield (max_length=30) authors = models. Manytomanyfield (Author) def __unicode__ (self): return Self.name
3. Synchronize the database:
[email protected]:/home/uu/work/csct06# Lsblog csct06 Manage.py[email protected]:/home/uu/work/csct06# python manage.py syncdb ..... Creating tables ... creating table django_admin_logcreating table auth_permissioncreating Table auth_group_permissionscreating table auth_groupcreating table auth_user_groupscreating table Auth_user_user_ permissionscreating table auth_usercreating table django_content_typecreating table django_sessioncreating table Blog_ authorcreating table blog_book_authorscreating Table Blog_book you just installed Django ' s auth system, which means You don ' t has any superusers defined. Would to create one now? (yes/no): Yesusername (leave blank to use ' root '): Uuemail address: [Email protected]password:password (again): Supe Ruser created successfully. Installing Custom SQL ... Installing indexes ... Installed 0 object (s) from 0 fixture (s)
The green section is the generated database, and the resulting data file is Db.sqlite3:
[Email protected]:/home/uu/work/csct06# lsblog csct06 db.sqlite3 manage.py
Encountered a small problem that used to be MySQL,
[Email protected]:/home/uu/work/csct06# sqlite3 db.sqlite3
The program "Sqlite3" has not been installed. You can use the following command to install:
Apt-get Install Sqlite3
Just follow the prompts, okay?
#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>
Well, you can manipulate the database.
4. Operation Database:
• 1 View the resulting database tables:
sqlite>. Tablesauth_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
• 2 Enter the interpreter to organize the data
1) Encounter a minor problem:
[Email protected]:/home/uu/work/csct06# ipython manage.py Shell
The program "Ipython" has not been installed. You can use the following command to install:
Apt-get Install Ipython
According to the operation,
#apt-get Install Ipython
It's out of the problem.
[email protected]:/home/uu/work/csct06# ipython manage.py shellUsage: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 T He Python path to a settings module, e.g. "Myproject.settings.main". If this isn ' t provided, the DJANGO_SETTINGS_MODULE environment variable would 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 Exittype ' manage.py Help<subcommand>' For help on a specific subcommand. Available Subcommands:[auth] ChangePassword Createsuperuser[django] Check cleanup compilemessages create Cachetable 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] Collect Static findstatic runserver[email protected]:/home/uu/work/csct06# lsblog csct06 db.sqlite3 manage.py[email& nbsp;protected]:/home/uu/work/csct06# Ipip Ipod-read-sysinfo-extendedip6tables Ipod-time-syncip6tables-apply Ippfindip6tables-restore Ipptoolip6tables-save IPROXYIPCL Uster IPTABLESIPCMK Iptables-applyipcontroller iptables-restoreipcrm iptables-saveipcs Iptables-xmlipengine Iptun Neliplogger ipythonipmaddr ipython2.7[email protected]:/home/uu/work/csct06# I python2.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 has been moved to the top ' IPython ' level. Warn ("The top-level ' frontend ' package has been deprecated." ---------------------------------------------------------------------------Multipleinstanceerror Trace Back (most recent)/usr/lib/python2.7/dist-packages/ipython/utils/py3compat.pyc in execfile (fname, *where) 20 2 else:203 filename = fname--> 204 __builtin__.execfile (filename, *where)/h ome/uu/work/csct06/manage.py in<Module>() 8 from django.core.management import execute_from_command_line 9---> 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/pytho N2.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) 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.R Equires_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 i F 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/cor E/management/commands/shell.pyc in Handle_noargs (self, **options) raise Importerror---> Bayi Self.run_shell (shell=interface) except importerror:83 import code/usr/local /lib/python2.7/dist-packAges/django/core/management/commands/shell.pyc in Run_shell (self, Shell)-for-Shell in Available_shells: Try:---> getattr return (Self, Shell) () except importerror:63 Pass/usr/local/lib/python2.7/dist-packages/django/core/management/commands/shell.pyc in Ipython (self) For IP in (Self._ipython, self._ipython_pre_100, self._ipython_pre_011): try:---> 44 IP () except importerror:46 pass/usr/local/lib/python2.7/dist-packages /django/core/management/commands/shell.pyc in _ipython (self) "" "" Start Ipython >= 1.0 "" "Panax Notoginseng F Rom IPython import Start_ipython---> Start_ipython (argv=[]) Max def IPython (self):/usr/lib/py Thon2.7/dist-packages/ipython/__init__.pyc in Start_ipython (argv, **kwargs) "" "117 from Ipython.termina L.ipapp Import Launch_neW_instance--> 118 return Launch_new_instance (ARGV=ARGV, **kwargs) 119-def start_kernel (Argv=none, **kwar GS):/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 '--&G T Being '%s is created. '% cls.__name__ 361) 362 Multipleinstanceerror:multiple Inc Ompatible subclass instances of Terminalipythonapp is being created.
View Code
The command has been faulted because it is the following command:
# python manage.py Shell
Create a total of four
[email protected]:/home/uu/work/csct06# python manage.py shellpython 2.7.6 (default, Mar 22 2014, 22:59:56) .... Proceed as follows: in [1]: From blog.models import Author,bookin [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 () error here in [9]: Authors---------------------------------------------------------------------------Nameerror Traceback (most recent)<ipython-input-9-07dd264ecf4d>Inch<Module>()----> 1 authorsnameerror:name ' authors ' is not defined follow the steps below to resolve
Direct query all in [all]: Author.objects.all () out[11]: [<Author:Tom1>,<Author:Tom2>,<Author:Bob1>,<Author:Bob2>] Query all results by assignment: in [[]: Author = Author.objects.all () in []: authorout[13]: [<Author:Tom1>,<Author:Tom2>,<Author:Bob1>,<Author:Bob2>]
in [+]: B1 = Book () get B1 object in [[]: B1.name = ' Java ' add first books: Javain [+]: B1.save () Save with Sava method
Add in [] for book Java: tom1 = Author.objects.get (name_exact= ' Tom1 ')----------------------------------------------------- ----------------------Fielderror Traceback (most recent) ... Name_exact method Error, Processing: in [+]: tom1 = Author.objects.get (name= ' Tom1 ')
In []: tom1
OUT[22]: <Author:Tom1>
Add a first
In [23°c]: B1.authors.add (TOM1)
Add success:
In []: B1.authors.all ()
OUT[24]: [<author:tom1>]
Add a second
In []: B1.authors.add (author[2])
in [+]: B1.authors.all ()
OUT[27]: [<author:tom1>, <author:bob1>]
Third author, pay attention to the subscript:
In []: B1.authors.add (author[1])
In []: B1.authors.all ()
OUT[29]: [<author:tom1>, <author:tom2>, <author:bob1>]
To delete an author, call the Remove method:
in [+]: B1.authors.remove (TOM1)
Use the all method for all queries:
In [to]: B1.authors.all ()
OUT[31]: [<author:tom2>, <author:bob1>]
Use the filter method to make a partial query:
In [to]: B1.authors.all ()
OUT[31]: [<author:tom2>, <author:bob1>]
The author of Tom1 has been deleted here, so the query is not:
in [+]: B1.authors.filter (name= ' Tom1 ')
OUT[32]: []
in [[]: B1.authors.filter (name= ' Tom2 ')
OUT[33]: [<author:tom2>]
In [tom1 ]: < Tom1>in [+]: Tom1.book_set.all () set is a collection or can be considered an object out[35]: []in [36]: Tom1.book_set.add (B1) also uses the Add method to add a book to the author, which is the previous book Java
In [MAX]: tom1.book_set.create (name= "python") add a second book
OUT[40]: <Book:python>
In [total]: Tom1.book_set.all () added two books for tom1
OUT[41]: [<book:java>, <book:python>]
In [all]: Book = Book.objects.all () find a collection of books
in [+]: Book
OUT[43]: [<book:java>, <book:python>]
In []: Tom1.book_set.remove (book[0]) remove a book
In [the]: Tom1.book_set.all ()
OUT[45]: [<book:python>]
Various module Learning Daquan:
http://blog.csdn.net/lcyangcss/article/details/7249961
Django Notes-model data template rendering process record (many-to-many relationships)