Django study notes THOUSAND AND THIRTY - using a database of ORM (with modifications)

Django framework basically want to use a combination of database and I talked about before use SQLAlchemy framework , Django is not supported by SQLAlchemy, but also embedded ORM framework, you may not need to directly face database programming, and can be defined by model class, additions and deletions to the data table implemented by object-oriented way change search.

Click to view the official documentation

Create a table

Correspondence between the ORM and DB

By the following graphic look at the correspondence between ORM and DB

Create a database

And almost SQLAlchemy, Django database must manually create the database.

Let's create a database called DjangoDB.

mysql> create database djangoDB charset=utf8;

 Our previous correspondence between object-oriented thinking --ORM talked about the ORM and DB

Create a class - table

So where is the class to put it? Remember in the last chapter, when speaking of APP, the APP file folder, there are two models of the file it? Yes, that is written here.

class User(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(null=False,max_length=20)
    age = models.IntegerField()
AutoField: automatic growth of IntegerField, when you do not specify Django will automatically create a property called id attribute automatic growth
BooleanField: Boolean field, a value of True or False
NullBooleanField: support Null, True, False three values
As CharField (MAX_LENGTH = 20 is ): String
Max_length parameter indicates the maximum number of characters
Use large text fields, generally more than 4000 characters: TextFiled
IntegerField: integer
DecimalField (max_digits = None, decimal_places = None): Decimal floating point precision can be specified
Max_digits parameter represents the total number of digits
Parameter represents the number of decimal places decimal_places
FloatField (): Float 
DateField[auto_now=False, auto_now_add=False]):日期
Auto_now parameters indicate each time to save the object, the field is automatically set to the current time, for the " last modified " timestamp, it always uses the current date, the default is false
Auto_now_add parameter represents the current time is automatically set when an object is first created, a time stamp is created, it always uses the current date, the default is false
Auto_now_add and auto_now parameters are mutually exclusive, the combination of errors will occur
TimeField: DateField parameters and the same
DateTimeField: date, parameter with the DateField
FileField: Upload file field, in binary form
ImageField: inherited FileField, to verify the content uploaded to ensure a valid image
Field Type
null : If True, representation allows empty, the default value is False
blank: If True, this field is blank allows default is False    
Contrast: null database concept category, blank areas form validation is
db_column: name of the field, if not specified, the name attribute is used (only the name of the database table name or a category attribute database operations)
db_index: If the value is True, then the table will create an index for this field, the default value is False (in order to optimize the query speed)
default: default value, which may be a value or a callable object. If you can call it every time you create a new object will call it.
primary_key: If True, the field will be the primary key field model, the default value is False, generally as an option of using AutoField
unique: If True, this field must have a unique value in the table, this value can not be repeated, the default value is False
Field Options

This class defines our table --id, name and age have a three fields. Note that class inheritance , do not wrong.

Database Configuration

To configure the following Django database ,, Because we are using MySQL, will be configured in setting.py part of the database file, the first configuration bile code shown below

Such modifications should be completed

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',   #指定数据库——MySQL
        'HOST':'127.0.0.1',                     #连接IP
        'PORT':3306,                            #端口:3306
        'NAME':'test',                          #database名称
        'USER':'root',                          #用户名
        'PASSWORD':''                           #密码
    }
}

有个问题,Django默认的MySQL的API好像是MySQLdb,但是python3已经不支持了,我们要使用pymysql来替代他,(直接进行表的创建的时候会发现建议我们使用mysqlclient,可以用pip直接安装)

 

在网上查了查,据说mysqlclient的稳定性不如pymysql,但是效率好像高一些。所以我们还是使用pymysql。要在项目的__init__.py中指明我们所用的API(注意是项目的py文件不是APP的)

#__init__.py文件
import pymysql
pymysql.install_as_MySQLdb()    #告诉Django用pymysql来替代默认的MySQLdb

生成table

下面就要我们通过mange.py来创建表

python manage.py makemigrations
python manage.py migrate

第一条语句是用来对类进行比较,看看是否有变化,第二条语句是把对应的变化体现在MySQL的表里。执行的效果

      

第二条指令执行完毕,可以在MySQL里看看创建的表

 

 注意第一个table的名字,就是依据我们的User那个表创建的。我们还可以看一下这个表的结构

 

 是不是跟我们定义的类是一样的!

表的删除和修改

表的修改 

如果我们想对表进行修改,或删除,只需要对前面创建的类进行修改后重新执行下面两段代码就可以了

python manage.py makemigrations
python manage.py migrate

我在类最后添加了一个字段,第一个命令后会问是否执行

 

 我们选择1以后会弹出一个python的解释器,按照要求输入

>>> timezone.now

这里有个深坑:

在添加字段的时候会报错:

django.db.utils.InternalError: (1067, "Invalid default value for‘name1’)

上面name1是新建的字段名,据说是字符集存在问题。

 

就可以了。不过在此期间出现了一堆错误,后来不知道怎么跑了一遍就有好了。

表的删除

如果想删除这个表,只需要把表对应的类注释掉(注意注释掉就可以了,不用删除。)

数据操作

 数据的操作我们还是从增删改查四个方面来说

数据添加

数据添加要先实例化一个对象

models.User.objects.create(name="张三")

可以直接用类的objects.create的方式

数据查询

基本查询

  1. get()——查询单一结果,如果不存在会抛出模型类DoesNotExist异常
  2. all()——查询多个结果
  3. count()——查询结果数量。

过滤查询

过滤查询可以实现SQL语句中的where的功能,包括下面的方法

  1. filter()——过滤出多个结果
  2. exclude()——排除掉符合条件剩下的结果
  3. get()——过滤单一结果

过滤查询的条件也是很多种的

 

Guess you like

Origin www.cnblogs.com/yinsedeyinse/p/12368859.html
Recommended