Python Learning Day 68th: database-related operations

Source: Internet
Author: User

ORM Introduction
orm能干的事:1 创建表,修改表,删除表2 插入数据3 修改数据4 删除数据不能干:不能创建数据库类名-----》表对象------》一条数据属性-----》字段
An ORM "Object-relation-mapping" abbreviation
#sqlThe table in the #Creating table: CREATE TABLE employee (ID INT PRIMARY KEY auto_increment, Name VARCHAR, gender BITDefault 1, Birthday DATA,                                        Department VARCHAR, Salary DECIMAL (8,2) unsigned,  ); #sqlIn the table record #Add a table record: INSERT employee (name,gender,birthday,salary,department) VALUES ("Alex", 1,"1985-12-12", 8000,"Cleaning department "); #Query a table record: SELECT *From Employee WHEREage=24; #Update a table record: Update employeeSETbirthday="1989-10-24" WHEREid=1; #Delete a table record: deleteFrom Employee WHEREName="Alex"#pythonClass Employee (models. Model):Id=models. Autofield (Primary_key=true)Name=models. Charfield (MAX_LENGTH=32)Gender=models. Booleanfield () birthday=models. Datefield () department=models. Charfield (max_length=32) salary=models. Decimalfield (max_digits=8,decimal_places=2) #python Class object # Add a table record: Emp=employee (name= "Alex", gender= True,birthday= "1985-12-12", epartment= " Cleaning Department") Emp.save () # query a table record: Employee.objects.filter (age=24) # Update a table record: Employee.objects.filter (id=1). Update (birthday= "1989-10-24") # delete a table record: Employee.objects.filter (name="Alex"). Delete ()          
Using MySQL steps
0  CREATE DATABASE (Orm Cannot create DATABASE) Span class= "Hljs-number" >1  in Settings configure 2 The span class= "Zh-hans" in Zh-hans Init.py3  define classes in Models4  write attribute, corresponding to the database field 5  Execute python manage.py makemigrations (6  execute Pyhton manage.py migrate ( The table name created is App     
Settings configuration
DATABASES = {' Default ': {' ENGINE ':' Django.db.backends.mysql ',' NAME ':' Lqz ',' USER ':' Root ',' PASSWORD ': '123456 ',' HOST ': '127.0.0.1 ',' PORT ':3306,' Atomic_request ':True,' OPTIONS ': {"Init_command":"SET Storage_engine=myisam",}}}‘‘‘' NAME ':To connect to the database, you need to create a good before connecting' USER ':User name of the connection database' PASSWORD ':Connect database Password ' host ': connect host, default native ' Port ': port default 3306' atomic_request ': True, set to  True  All SQL corresponding to the unified HTTP request is executed in one transaction (either all succeeds or all fails). is a global configuration, if you want to drain an HTTP request (and then customize the transaction), you can use the non_atomic_requests decorator ' OPTIONS ': { "Init_ Command ": " Set Storage_engine=myisam ",} sets the storage engine that created the table to MyISAM, INNODB     
Query for Table
<1>All ():Query all results<2>Filter (**kwargs):It contains objects that match the filter criteria given<3>Get (**kwargs):Returns the object that matches the filter criteria given, with only one return result,If there are more than one object that meets the filter criteria or no error is thrown.<4> Exclude (**kwargs):It contains objects that do not match the filter criteria given<5> order_by (*field):Sort the results of a query<6>Reverse ():Reverse order of query results<8>Count ():Returns a matching query in the database (QuerySet)The number of objects.<9>First ():Returns the first record<10> Last (): returns the final record <11> exists (): Returns true if Queryset contains data,otherwise returns false <12> VALUES (*field): Returns a Valuequeryset-a special querysetthat is not instantiated by a series of model objects after it has been run . It's an iterative dictionary sequence <13> values_list (*field): It's   very similar to values (), it returns a tuple sequence,values  Returns a dictionary sequence <14> distinct (): rejects duplicate records from the returned results         
Table Relationship Creation
一个出版社可以出版多本书,一本书只能有一个出版社一对多(一旦确立了一对多的关系,关联字段要放在多的表里)models.ForeignKey(to=‘Publish‘,to_field=‘nid‘,on_delete=models.CASCADE)一个作者可以写多本书,一本书可以有多个作者多对多(需要第三张表)models.ManyToManyField(to=‘Author‘)一对一author和author_detail是一对一models.OneToOneField(to=‘AuthorDatail‘,to_field=‘nid‘,unique=True,on_delete=models.CASCADE)

Python Learning Day 68th: database-related operations

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.