I. Database configuration 1.django default support Sqlite,mysql, Oracle,postgresql database.
- Django uses SQLite's database by default, default with SQLite database driver, engine name: Django.db.backends.sqlite3
- Engine Name: Django.db.backends.mysql
2. The SQLite database is used by default in Django projects, with the following settings in Settings:
DATABASES = {' default ': { ' ENGINE ': ' Django.db.backends.sqlite3 ', ' NAME ': Os.path.join (Base_dir, ' Db.sqlite3 '), }}
If we want to change to a MySQL database, we need to modify the following:
DATABASES = {' default ': { ' ENGINE ': ' Django.db.backends.mysql ', ' NAME ': ' Books ', #你的数据库名称 ' USER ': ' Root ', #你的数据库用户名 ' PASSWORD ': ', #你的数据库密码 ' HOST ': ', #你的数据库主机, leave blank default to localhost ' PORT ': ' 3306 ' , #你的数据库端口 }}
Attention:
Name is the name of the database, the database must have been created before the MySQL connection, and the db.sqlite3 under the SQLite database above is automatically created by the project
User and password are the username and password of the database respectively.
Once setup is complete, we need to activate our MySQL before starting our Django project.
Then, start the project and will error: no module named MySQLdb
This is because Django defaults to the driver you are importing is MYSQLDB, but MySQLdb is a big problem for py3, so the driver we need is pymysql
So, we just need to find the project name file under the __init__, which is written in:
Import Pymysql
Pymysql.install_as_mysqldb ()
Two. ORM Table model
Author Model: An author has a name.
Author detailed model: Put the author's details into the details table, including the name, email address, the author's details model and the author model is a one-to one-to-one (similar to the relationship between everyone and his identity card), in most cases we do not need to split them into two tables, This is just a one-to-one concept.
Publisher Model: Publisher has name, address.
Book Model: books have the title and date of publication, a book may have multiple authors, an author can also write more than one book, so the relationship between the author and the book is a many-to-many relationship (Many-to-many), a book should only be published by a publisher, So publishers and books are a one-to-many correlation (One-to-many), also known as foreign keys.
The code is as follows:
From django.db import models# Author table Class Author (models. Model): name = models. Charfield (max_length=30) email = models. Emailfield () def __str__ (self): return self.name# Publishing house Class Publisher (models. Model): Press = models. Charfield (max_length=30) press_address = models. Charfield (max_length=30) # Bookclass book (models. Model): title = models. Charfield (max_length=100) Price = models. Decimalfield (max_digits=5, decimal_places=2, default=10) publication_date = models. Datefield () author = models. Manytomanyfield (Author) publisher = models. ForeignKey (Publisher) # The database is saved with publish_id def __str__ (self): return Self.title
Analysis Code:
<1> Each data model is a subclass of Django.db.models.Model, and its parent class model contains all the necessary methods for interacting with the database. and provides a nice introduction to the syntax for defining database fields.
<2> each model is equivalent to a single database table (a many-to-many relationship exception that generates a relational table), and each property is also a field in the table. The property name is the field name, and its type (for example, Charfield) corresponds to the field type of the database (for example, varchar). You can be aware of the other types that correspond to what fields are in the database.
Three relationships between <3> models: one-to-one, one-to-many, many-to-many.
One: The essence is in the main foreign key (author_id is foreign key) on the basis of the foreign key to add a unique=true attribute;
One-to-many: is the primary foreign key relationship; (foreign key)
Many-to-many: (Manytomanyfield) automatically creates a third table (and of course we can create a third table ourselves: two foreign key)
2.1ORM Increase
From app01.models Import * #create方式一: Author.objects.create (name= ' Alvin ') #create方式二: Author.objects.create (**{"name": "Alex"}) #save方式一: author=author (name= "Alvin") Author.save () # Save Mode II: author=author () author.name= "Alvin" Author.save ()
The point is,------->. So how do you create a book that has a one-to-many or many-to-many relationship? (How to handle fields of foreign key relationships as many as
publisher和
Many-to-many authors)
#一对多 (ForeignKey): #方式一: Because of binding a one-to-many field, such as publish, the field stored in the database is named publish_id, so we can set the corresponding value directly to the # field: Book.objec Ts.create (title= ' php ', publisher_id=2, #这里的2是指为该book对象绑定了Publisher表中id =2 Line Object Publication_date= ' 2017-7-7 ', price=99) #方式二: # <1> get to bind first Publisher object: Pub_obj=publisher (name= ' River Big Publishing house ', address= ' Baoding ', city= ' Baoding ', state_province= ' Hebei ', country= ' Ch Ina ', website= ' http://www.hbu.com ') OR pub_obj=publisher.objects.get (id=1) # <2> change publisher_id=2 to Pub lisher=pub_obj# Many-to-many (Manytomanyfield ()): Author1=author.objects.get (id=1) author2=author.objects.filter (name= ' Alvin ') [0] Book=book.objects.get (id=1) book.authors.add (Author1,author2) #等同于: Book.authors.add (*[author1,auth OR2]) Book.authors.remove (*[author1,author2]) #-------------------Book=models. Book.objects.filter (id__gt=1) authors=models. Author.objects.filter (id=1) [0] Authors.book_set.add (*book) Authors.book_set.remove (*book) #-------------------Book.authors.add ( 1) book.authors.remove (1) authors.book_set.add (1) authors.book_set.remove (1) #注意: If the third table is through models. Manytomanyfield () is created automatically, then the binding relationship is only one of the above # if the third table is created by itself: Class Book2author (models. Model): Author=models. ForeignKey ("Author") book= models. ForeignKey ("book") # Then there is another way: Author_obj=models. Author.objects.filter (id=2) [0] book_obj =models. Book.objects.filter (id=3) [0] s=models. Book2Author.objects.create (author_id=1,book_id=2) s.save () s=models. Book2author (author=author_obj,book_id=1) S.save ()
Deletion of 2.2ORM (delete)
Book.objects.filter (id=1). Delete ()
We deleted a piece of information on the surface, actually deleted three, because we deleted the book in the Book_authors table has two related information, this deletion method is django default cascade delete.
2.3ORM Change (update and save)
Instance:
Attention:
<1> the second way to modify cannot use get is because update is a method of the Queryset object, get returns a model object, it does not have an Update method, and filter returns a Queryset object ( The conditions within the filter may have multiple conditions, such as Name= ' Alvin ', which may have two rows of Name= ' Alvin '.
<2> in the Insert and Update Data section, we refer to the Save () method of the model, which updates all the columns in a row. In some cases, we just need to update a few columns in the row.
#----------------The Update method directly sets the corresponding property---------------- models. Book.objects.filter (id=3). Update (title= "PHP") # #sql: # #UPDATE "App01_book" SET "title" = ' php ' WHERE "app01_ Book "." id "= 3; args= (' PHP ', 3) #---------------The Save method will reset all properties again, inefficient----------- obj=models. Book.objects.filter (id=3) [0] obj.title= "Python" obj.save () # Select "App01_book". " ID "," App01_book "." Title "," App01_book "." Price ", #" App01_book "." Color "," App01_book "." Page_num ", #" App01_book "." publisher_id "from" App01_book "WHERE" App01_book "." id "= 3 LIMIT 1; # # UPDATE "App01_book" SET "title" = ' Python ', "price" = 3333, "color" = ' red ', "page_num" = 556,# "publisher_id" = 1 WHE RE "App01_book". " id "= 3;
In addition, the update () method is valid for any result set (QuerySet), which means that you can update multiple records at the same time the update () method returns an integer value that represents the number of record bars affected.
Note that the query property is not available because update returns a shape, and for each object you create, you want to display the corresponding raw SQL in the settings plus the logging section:
LOGGING = { ' version ': 1, ' disable_existing_loggers ': False, ' handlers ': { ' console ': { ' level ': ' DEBUG ', ' class ': ' Logging. Streamhandler ', }, }, ' loggers ': {' django.db.backends ': {' handlers ': [' console '], ' Propagate ': True, ' level ': ' DEBUG ', },} }
Database and ORM for Django Foundation