(4) Django framework learning-Model

Source: Internet
Author: User
Document directory
  • Use Model
  •  
  •  
Model use first install MySQL python connection driver, windows installation can download, corresponding to python-2.7: https://code.google.com/p/soemin/downloads/detail? Name‑mysql-python-1.2.3.win32-py2.7.exe & can = 2 & q = simple. the mysql database operations in view are displayed first.
FromDjango. shortcuts ImportRender_to_response
ImportMySQLdb

DefBook_list (request ):
Db = MySQLdb. connect (user = 'me', db = 'mydb', passwd = 'secret', host = 'localhost ')
Cursor = db. cursor ()
Cursor.exe cute ('select name FROM books order by name ')
Names = [row [0]ForRowInCursor. fetchall ()]
Db. close ()
ReturnRender_to_response('book_list.html ', {'names': names}) the above practices are relatively primitive and have some drawbacks: 1. hard-CODED database connection parameters. Ideally, these parameters should be placed in the configuration file. 2. fixed procedures, always open the connection, create a cursor, close the connection steps, there are too many repeated code 3. to bind a mysql database, if you want to switch to another database, there are too many modifications, and you need to change the connection parameters, maybe the SQL statement also needs to be modified, and the Django database API is created to solve the above problems.FromDjango. shortcutsImportRender_to_response
FromMysite. books. modelsImportBook

DefBook_list (request ):
Books = Book. objects. order_by ('name ')
ReturnRender_to_response('book_list.html ', {'books': books}) first in settings. in The py file, set database DATABASES = {'default': {'Engine ': 'django. db. backends. mysql ', # Add 'postgresql _ psycopg2', 'mysql', 'sqlite3 ', or 'oracle '. 'name': 'test', # database NAME. If sqlite3 is used, enter the database file path, for example, '/home/django/mydata. 'user': 'root', # Not used with sqlite3. 'Password': 'admin', # Not used with sqlite3. 'host': '', # Set to empty string Localhost. not used with sqlite3. 'Port': '', # Set to empty string for default. not used with sqlite3.} Once the database information is set, you can use python manage. test with py shell> from django. db import connection >>> cursor = connection. if no error is reported for cursor (), the configuration is normal. The following describes the differences between projects and apps: 1. A project is an instance of a series of app sets, and the configuration information of these apps. Specifically, the project only needs to provide a configuration file, including the database connection information, the list of installed apps, And the template path. 2. an app is a collection of reusable functions provided by Django, generally including modesl and views in the same package. For example, a Django project can be composed of multiple apps, such as a comment system and a background management system. All these apps can be reused in different projects and are independent, of course, it depends on your design... However, the app is not mandatory. view + template + urlconf can be used to build a project. However, in order to achieve reusability and to use Django's powerful database level api-model, to create an app, run the following command: python manage. py startapp books some people think that it is a bit redundant to re-define the field information in a data table in python. If you use the introspection operation of the database itself to determine the data model at runtime, is it more convenient? The answer is wrong. 1. When the latter is running, if every request is introspective about the table structure of the database, additional overhead will be generated and the system will be burdened. 2. Write the table structure in python code, which is easy to manage and operate. 3. Then, the Data Types in the database are relatively simple, while Django has a wide variety of data types, such as the mail address type and website type, which can increase productivity... One drawback of using python code to express data table information is that it must be consistent with the database table information. If either party modifies the data table, it must be modified. General steps for using model: 1. create the model subclass class Publisher (models. model): name = models. charField (max_length = 30) address = models. charField (max_length = 50) city = models. charField (max_length = 60) state_province = models. charField (max_length = 30) country = models. charField (max_length = 50) website = models. URLField () 2. then in settings. register Your appMIDDLEWARE_CLASSES = (# 'django. middleware. common. commonMiddleware ', # 'django. contrib. sessions. middleware. sessionMiddleware ', # 'django. contrib. auth. middleware. authenticationMiddleware ',) INSTALLED_APPS = (# 'django. contrib. auth ', # 'django. contrib. contenttypes ', # 'django. contrib. sessions ', # 'django. contrib. sites ', 'books', # note that this comma is added to differentiate the type of the tuples.And remember to use quotation marks...) 3. you can use commands to verify your settings. 0 errors indicates the correct python manage. py validate 4. you can use the python manage command to create a database table through the model class definition. py sqlall books # print the SQL statement for creating the corresponding data table python manage. py syncdb # runs the SQL statement directly to check whether the table exists. If not, create a new table. If the data in the model is changed, this statement is useless. 5. Use the model to insert a simple data table. Django writes data to the database until it saves. Python manage. py shell> from books. models import Publisher >>> p1 = Publisher (name = 'apress', address = '1970 Telegraph Avenue ',... city = 'berkeley ', state_province = 'CA', country = 'U. s. a. ',... website = 'HTTP: // www.apress.com/')> p1.save () query using manager> publisher_list = Publisher. objects. all () # Publisher. objects returns a manager >>> publisher_list [<Publisher: Publisher object >,< Publisher: Publisher object>] In this way, you can retrieve and record data, or other logic operations you have defined >>> publisher_list [0]. addressu '2855 Tele Avenur 'if you want to write data directly to the database without saving (), use the create () method of the Manager> p1 = Publisher. objects. create (name = 'apache ',... address = '1970 Telegraph Avenue ',... city = 'berkeley ', state_province = 'CA', country = 'U. s. a. ',... website = 'HTTP: // www.apress.com/') 6. in the model class, add the _ unicode _ () function to represent the string representation information of each class. It is equivalent to toString () def _ unicode _ (self): return self. name >>> [<Publisher: Apress>, <Publisher: O 'Reilly>] 7. the update operation simply assigns a new value, and then saves (). However, this is very efficient. The manager has an update function dedicated to update operations >>> Publisher. objects. filter (id = 52 ). update (name = 'apress Hing ') 8. conditional selection operation, using the filter function in manager, The QuerySet object is returned, similar to the result set object >>> Publisher. objects. filter (name = 'apache') [<Publisher: Apress>] More Complex Condition Selection operations are implemented using the lookup type modifier unique to Django> Pu Blisher. objects. filter (name _ contains = "press") [<Publisher: Apress>] _ contains: Fuzzy match operations similar to like in SQL statements: WHERE name LIKE '% press %'; to obtain a single object, use the get () function. If multiple objects are returned, the error MultipleObjectsReturned is returned. If the returned value is null, the error DoesNotExist is returned. >>> A = Publisher. objects. get (name = "Apress") >>> a <Publisher: Apress >>>. addressu '2855 Tele Avenur 'can also be used to retrieve record data, which is equivalent to extracting a Publisher record object. 9. sort operation >>> Publisher. objects. order_by ("state_province", "address") [<Publisher: Apress >,< Publisher: O 'Reilly>] >>> Publisher. objects. order_by ("-name") # '-' indicates that the reverse query set can also use the index value Publisher as in the list. objects. order_by ("address") [1] but does not support negative Publisher. objects. order_by ("address") [-1] can be expressed in reverse order: Publisher. objects. order_by ("-address") [0] 10. the delete record operation has the corresponding delete () function for a single model class or QuerySet class> p = Publisher. objects. get (name = "O 'Reilly")> p. delete () >>> Publisher. objects. filter (country = 'usa '). delete () >>> Publisher. objects. all (). delete () # If you want to clear the data table, call all () explicitly and then delete

Publish by note

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.