Python notes (vi)-model and Django site management

Source: Internet
Author: User

In this post, you'll learn about Django's interaction with the database. First download python for MySQL online and then install it. After the installation is successful, mount it in the setting.py file as follows:

1DATABASES = {2     'default': {3         'ENGINE':'Django.db.backends.mysql',4         'NAME':'Database',#the first thing to do in MySQL is to create a database called5         'USER':'Root',#users of your database6         'PASSWORD':'Root',#the password for your database7         'HOST':'127.0.0.1',8         'PORT':'3306'9     }Ten}

Once configured, enter the directory where the project is located and run the Python manage.py shell on the command line to test it. If entering the following code does not show any error message, it proves that your database configuration is correct. After that, it is possible to make additional deletions and check operations.

1  from Import Connection 2 cursor = Connection.cursor ()

Let's say your database is configured correctly. We will show you how to do the increase and deletion check operation.

First add a model to the app, and I've added 3 here, as follows:

1 #Encoding=utf-82  fromDjango.dbImportModels3 4 #build a model that corresponds to a table in MySQL5 #Create your models here.6     7 classPublisher (models. Model):8Name = models. Charfield (max_length = 30)#field names and type designations9Address = models. Charfield (max_length = 50)TenCity = models. Charfield (max_length = 50) OneState_province = models. Charfield (max_length = 50) ACountry = models. Charfield (max_length = 50,blank=true)#Blank=true indicates that the field can be empty -Website = models. Urlfield (Blank=true)#specific URL forms provided by Python -      the     def __unicode__(self):#equivalent to ToString () in Java -         returnU'id=%d,name=%s'%(Self.id,self.name) -      -     classMeta:#The result set that is specified is followed by the ascending order of the IDs, and the use of ordering=['-id ') is descending. +ordering = ['ID'] -          + classAuthor (models. Model): AFirst_Name = models. Charfield (max_length = 50) atLast_Name = models. Charfield (max_length = 50) -email = models. Emailfield ()#specific email format provided by Python x -      -     def __unicode__(self): -         returnU'firstname=%s'%Self.first_name -      in     classMeta: -ordering = ['ID'] to      + classBook (models. Model): -title = models. Charfield (max_length = 50) theAuthor = models. Manytomanyfield (Author)#Book and author for many-to-many *Publisher = models. ForeignKey (Publisher)#FOREIGN Key $Publication_date = models. Datefield ()#specific date formats provided by PythonPanax Notoginseng      -     def __unicode__(self): the         returnSelf.title +      A     classMeta: theordering = ['ID']

The above code can be easily understood by referring to the subsequent comments. After a good CV model (the model corresponds to our table in the database), we register our project in the Installed_apps tuple in setting.py. Then use the Python manage.py syncdb command to create the tables in the database. After a successful creation, the database is manipulated in tests.py (not necessarily in this file).

  Inserting data

Let's look at the following code:

1 #Encoding=utf-82 #Create your tests here.3  fromSecond.modelsImportPublisher4 #inserting Objects5P1 = Publisher (name='Zhouxy', address='Nenu-software', city='Changchun', state_province='CA', country=' China', website='Www.cnblogs.com/zhouxuanyu')6 P1.save ();7P2 = Publisher (name='Zhouxuanyu', address='Nenu-software', city='Changchun', state_province='CA', country=' China', website='Www.cnblogs.com/zxyyxzshine')8 P2.save ();9Publisher_list =Publisher.objects.all ();Ten PrintPublisher_list

In the 5th, 7 lines above, create two object p1,p2. Then we call their save () method separately and insert it into the database. The 9,10 line prints out the information for both objects. The printed information is the value returned by the __UNICODE__ function that we defined when we defined publisher in model. is similar to ToString () of an object in Java. Here is the result graph:

We can use the Python manage.py sqlall second command to display the MySQL syntax. (Layout reason, I only cut part of the picture)

  Querying data

1 #Querying Objects2 PrintPublisher.objects.filter (name='Zhouxy'). Order_by ('ID')#equivalent to using the WHERE keyword in sql, you can also add Class Meta in Model:3 PrintPublisher.objects.filter (name='Zhouxy', city='Changchun')#equivalent to using the where and the and keyword in SQL4 PrintPublisher.objects.filter (name__contains='Zhouxy') [0:2]#The SQL default = operator is an exact match, the field __contains is equivalent to the like in SQL, and the slice operator is equivalent to offset in SQL. Limit:5 PrintPublisher.objects.get (name='Zxyyxzshine', id=2)#get a single object

It is easy to understand the comparison notes. Filter () is equivalent to the WHERE keyword in SQL. Order_by () is equivalent to the ORDER BY statement in SQL. If more than one condition is added to the filter, it is equivalent to using the AND keyword in a conditional statement in SQL to combine the conditions.

  Update data

1 # Updating Objects 2 Print Publisher.objects.filter (id=1). Update (name="zxyyxzshine"# Returns the number of successfully updated row  3print Publisher.objects.filter (name='zhouxuanyu'). Update (name='zxyyxzshine')

  Delete Object

1 # Delete Object 2 Print Publisher.objects.filter (id=1). Delete ()  3print Publisher.objects.all (). Delete ()

Python notes (vi)-model and Django site management

Related Article

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.