DAY63: Database and ORM

Source: Internet
Author: User
Tags sqlite sqlite database python mysql

First, the configuration of the database 1 Django default support Sqlite,mysql, Oracle,postgresql database.

<1> SQLite

Django uses SQLite's database by default, with SQLite's database driver default.

Engine Name: Django.db.backends.sqlite3

<2> MySQL

Engine Name: Django.db.backends.mysql

2 MySQL Driver
    • MySQLdb (MySQL python)
    • Mysqlclient
    • Mysql
    • Pymysql (pure python mysql driver)
3 The SQLite database is used by default in Django projects, with the following settings in Settings:

If we want to change the 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 ' , #你的数据库端口    }}
View Code

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 the project automatically created user name and password for the database, respectively, users and password. Once setup is complete, we need to activate our MySQL before starting our Django project. Then, the startup project will be error: No module named MySQLdb this is because Django defaults to the driver you import 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__, write in it: Import pymysqlpymysql.install_as_mysqldb () problem solved!
Second, the ORM Table Model table (model) Creation:

Example: Let's assume that the following concepts, fields and relationships

Author Model: An author has a name.

Author detailed model: Put the author's details into the details table, including the gender, email address and date of birth, the author details model and the author model is a one-to one-to-one (similar to the relationship between each person and his identity card), In most cases we do not need to split them into two tables, which only leads to a one-to-many concept.

Publisher model: Publishers have names, addresses, cities, provinces, countries, and websites.

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.

From django.db import Models<BR>Class Publisher (models. Model): name = models. Charfield (max_length=30, verbose_name= "name") address = models. Charfield ("Address", max_length=50) City = models. Charfield (' City ', max_length=60) state_province = models. Charfield (max_length=30) country = models. Charfield (max_length=50) website = models.        Urlfield () class meta:verbose_name = ' publisher ' verbose_name_plural = Verbose_name def __str__ (self): Return Self.name class Author (models. Model): name = models. Charfield (MAX_LENGTH=30) def __str__ (self): Return Self.name class Authordetail (models. Model): Sex = models. Booleanfield (max_length=1, choices= (0, ' Male '), (1, ' female '),)) e-mail = models. Emailfield () address = models. Charfield (max_length=50) birthday = models. Datefield () Author = models. Onetoonefield (Author) class book (Models. Model): title = models. Charfield (max_length=100) authors = models. Manytomanyfield (Author) publisher = models. ForeignKey (Publisher) Publication_datE = models. Datefield () price=models. Decimalfield (max_digits=5,decimal_places=2,default=10) def __str__ (self): return Self.title
View Code

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)

1. Orm Increase (Create,save)
 from  app01.models import  * #  create mode one: Author.objects.create (name= ' Alvin ')  Span style= "COLOR: #008000" >#  create Way II: Author.objects.create (**{"name": "Alex "})  #  save Way One: Author=author (name=" Alvin " )   Author.save ()  #save Way Two: 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)

#One -to-many (ForeignKey):    #mode one: due to binding a pair of fields, such as publish, the field stored in the database is called publish_id, so we can directly to this    #field to set the corresponding value:Book.objects.create (title='PHP', publisher_id=2,#the 2 here refers to a row object that is bound to the id=2 in the Publisher table for the book objectPublication_date='2017-7-7', Price=99)    #Way Two:    #<1> Get the Publisher object you want to bind first:Pub_obj=publisher (name='River Large Publishing house', address='Baoding', city='Baoding', State_province='Hebei', country=' China', website='http://www.hbu.com') OR Pub_obj=publisher.objects.get (id=1)    #<2> Change publisher_id=2 to Publisher=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)#equivalent to:Book.authors.add (*[Author1,author2]) 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)#Note: If the third table is through models. Manytomanyfield () is created automatically, then the binding relationship is only one way#If the third table was created by yourself:     classBook2author (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 ()
2, the ORM Delete (delete)
>>> Book.objects.filter (id=1). Delete () (3, {'app01. Book_authors'app01. book': 1})

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.

DAY63: Database and ORM

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.