Django's ORM Object Relational Model

  • Or MVC MVC framework includes an important part, is ORM, which implements the decoupling of the data model and the database, namely the design of the data model does not need to depend on a specific database by simple configuration database can easily be replaced, this pole large reduce the workload of developers, because the database does not need to face the changes caused by inefficiencies
  • ORM is "object - relational - mapping" for short. (Object Relational Mapping, referred to as ORM) (the future will learn a sqlalchemy, and he was like, but the django orm no independent for others to use, although more powerful than sqlalchemy, but others impossible)
  • When using the MySQL database: Classes and Objects ---> sql ---> pymysql ---> mysql server ---> disk, orm in fact, the grammar-translation engine class object into a sql statement.

 

 

Sql and orm comparison :

Sql statement operation:

Create a table:

create table book(

    id int primary key auto_increment,

    name char(20) not null,

    price float(8,2) not null,

    date date not null,

    publisher varchar(32) not null

)

Table recording operation:

increase:

INTO INSERT Book values ( 1 , " perfect life ", 10.00 , '2019-05-24' , ' the future of publishing house ");

delete:

delete from book where id=1

change:

update book set price='20.00' where id=1;

check:

select * from book;

select * from book where id=1;

 

 

orm operation of the database:

app application models.py define classes:

    from django.db import models

# Orm class corresponding to the table name defined in the correspondence table attribute field

# Orm different types of call models classes are defined, constraints are not designated null default is NOT NULL, the maximum length of the string must be specified

# Orm no primary key is specified, a field is created automatically created when id primary key can be used id or pk use

class Book(models.Model):

    # id=models.AutoField(primary_key=True)

    name=models.CharField(max_length=20,null=True)

    price=models.FloatField()

    date=models.DateField()

    publisher=models.CharField(max_length=32)

Run created:

Tools--->Run managy.py Task:

命令:makemigrations --->   migrate

操作数据库表(在view视图中定义函数操作,先导入app应用中的models.py模块):

增:

# 第一种:实例化一个model对象,然后调用对象的save方法

obj=models.Book(name="完美人生",price=10.00,date='2019-05-24',publisher='未来出版社')

obj.save()

# 第二种:直接调用objects控制器的create方法(常用)

models.Book.objects.create(name="完美人生",price=10.00,date='2019-05-24',publisher='未来出版社')

 

删:

models.Book.objects.filter(id=1).delete()

 

改:

models.Book.objects.filter(id=3).update(price=20)

 

(get查询只能是有且只有一条记录符合查询结果,多或少都报错)

models.Book.objects.all()

models.Book.objects.filter(id=1) /models.Book.objects.get(id=1)

 

 

ORM对应关系:

--------------

类对象-----行记录

属性---------表字段

 

Guess you like

Origin www.cnblogs.com/open-yang/p/11221892.html