Django ORM single database table based on the model operation

Django ORM single database table based on the model operation

ORM introduction and basic usage

The ORM, O bject R & lt elational m apping, object-relational mapping is a method of using the database and the call in Django. ORM encapsulates SQL statements connections and operation of the database, we can be familiar with object-oriented code via Python implementation operation of the database, without having to remember complex SQL statements.

ORM greatly simplifies the code that we operate the database, but it would also cause some Efficiency. How to choose, look at the actual application needs.

use:

  1. Application folder below the models.pywrite data table corresponding to the class files, see the following example:

    class UserInfo(models.Model):
        id = models.AutoField(primary_key=True)  
        username = models.CharField(max_length=10)
        password = models.CharField(max_length=32)
  2. MySQL database to create a library, such as named orm01:

    create database orm01;
  3. Do the configuration database, the database is used by default lightweight SQLite:

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }

    To use the MySQL database, we need to settings.pyfile database configuration changes to the following format:

    #连接mysql的配置: 
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME':'orm01',
            'HOST':'127.0.0.1',
            'PORT':3306,
            'USER':'root',
            'PASSWORD':'123'
        }
    }
  4. In the project folder (project directory) under the __init__.pyfile write the following, to specify pymysqla connected client. Because although already pymyql local drive is installed, but Django MySQL connection MySQLdb still use the default drive, but MySQLdb does not support Python 3, so the need to manually configure the project.

    import pymysql
    pymysql.install_as_MySQLdb()
  5. Perform database synchronization instruction, execute the following code in a terminal:

    python manage.py makemigrations  #在migrations文件夹下面生成记录文件
    python manage.py migrate         #执行记录文件

In this way, the data table is created. Our table name default: application name _ the class name in lowercase.

In the terminal, you can see we have just built a database table through the commands.

1574244736504

ORM field corresponds to the actual field of relations with MySQL:

'AutoField': 'integer AUTO_INCREMENT',
'BigAutoField': 'bigint AUTO_INCREMENT',
'BinaryField': 'longblob',
'BooleanField': 'bool',
'CharField': 'varchar(%(max_length)s)',
'CommaSeparatedIntegerField': 'varchar(%(max_length)s)',
'DateField': 'date',
'DateTimeField': 'datetime',
'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)',
'DurationField': 'bigint',
'FileField': 'varchar(%(max_length)s)',
'FilePathField': 'varchar(%(max_length)s)',
'FloatField': 'double precision',
'IntegerField': 'integer',
'BigIntegerField': 'bigint',
'IPAddressField': 'char(15)',
'GenericIPAddressField': 'char(39)',
'NullBooleanField': 'bool',
'OneToOneField': 'integer',
'PositiveIntegerField': 'integer UNSIGNED',
'PositiveSmallIntegerField': 'smallint UNSIGNED',
'SlugField': 'varchar(%(max_length)s)',
'SmallIntegerField': 'smallint',
'TextField': 'longtext',
'TimeField': 'time',
'UUIDField': 'char(32)',

Specifying the name of the newly created data table

Sometimes, we do not want a table called the system default format, then, it can show the way by declaring that tells the system what the table name is:

from django.db import models

# Create your models here.
class Student(models.Model):
    # 模型字段
    name = models.CharField(max_length=100,verbose_name="姓名")
    sex = models.BooleanField(default=1,verbose_name="性别")
    age = models.IntegerField(verbose_name="年龄")
    class_number = models.CharField(max_length=5,verbose_name="班级编号")
    description = models.TextField(max_length=1000,verbose_name="个性签名")

    class Meta:
        db_table="tb_student"    # 指定表名为tb_student
        verbose_name = "学生"
        verbose_name_plural = verbose_name

Another effect of the specified table, if there is a database table, and individual fields to meet the requirements, there is no need for database migration can also use this table.

Deletions change search data in the table

Increase (created)

Save the model created by the class

obj = models.UserInfo(
    username='alex',
    password='sb'
)
obj.save()

Creating (used) by the create method

The return value is the record you create the create method of the object model

models.UserInfo.objects.create(
    username='一峰',
    password='666'
)

Modify (update)

Modified (conventional) update method by

First of all to find the model object data you want to modify, and then call the update method to be modified. update only querset type before calling, model object can not directly call the update method, so use the get method to get the object is not the time of update.

models.UserInfo.objects.filter(id=1).update(
    username='alexxx',
    password='bigsb',
)

By model object to save the changes (DRF will be used)

If the data is obtained by the object model can be modified by this update, modify model objects saved after the way the phenomenon of data.

obj = models.UserInfo.objects.filter(id=1)[0]
obj.username = 'alex222'
obj.password = '11111'
obj.save()

Bulk create

list_obj = []
for i in range(10):
    obj = models.UserInfo(
        username='xx%s'%i,
        password='66%s'%i,
    )
    list_obj.append(obj)
print(list_obj)
models.UserInfo.objects.bulk_create(list_obj)

update_or_create have updated, is not created

It should be noted that the data can only be found there is no or only one. If the condition of the data is more than one error.

a,b = models.UserInfo.objects.update_or_create(
    username='alex',
    defaults={
        'id':20,
        'password':'ooooo',
        'age':84,
    }
)
print(a)  # 当前更新后的model对象,或者是你新增的记录的model对象
print(b)  # 新增就是True,查询就False

delete

delete() The caller may be a method of the object model, it can be a queryset collection.

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

Inquire

Simple Query Examples

ret = models.UserInfo.objects.filter(id=1)
print(ret) #<QuerySet [<UserInfo: UserInfo object>]> -- []
obj = ret[0]
print(obj.id,obj.username)

Compare inquiry

Double underline by __adding commands, a simple comparison query, such determination is not empty, whether greater or less than a certain value:

article_list = Article.objects.filter(pub_date__isnull=False, pub_date__lte=datetime.now())

Such methods are commonly used:

isnull    # 字段为空
lt        # 小于
lte       # 小于等于
gt        # 大于
gte       # da'yu'deng'y

Query methods

A total of 13 methods, will know will be.

all()

All the results query, the result is the type of queryset

ret = models.UserInfo.objects.all()
filter(**kwargs)

It contains the given object matches the filter criteria, the result is queryset Type:

Book.objects.filter(title='linux',price=100)

A number of conditions which are separated by commas, and these conditions must be established, and the relationship is, or behind us to learn relations, direct written here is it working or is.

In addition to directly target objects, you can also use the filter method using queryest:

ret = models.UserInfo.objects.all().filter() 
get(**kwargs)

Returns object to match the filter, not queryset type, are rows object, and returns the results and only one target if they meet the filter criteria of more than one or no will throw an error. Catch the exception try.

Book.objects.get(id=1)
filter and compare get
ret = models.UserInfo.objects.get(age=18)
ret = models.UserInfo.objects.filter(age=180)
  • get only get a piece of data. If you can not find the super data or find two data will complain, get a request to return the result is that the object model rather than the query result set:
# 1 UserInfo matching query does not exist. 啥也没查到
# 2 get() returned more than one UserInfo -- it returned 11!  结果多了,不行! 
  • fitler not given, the result is a collection of queryset type, called a result set, which is a model of a target
exclude(**kwargs)

Means excluded, the object that contains the given filter condition does not match, no expensive operation not equal, with the exclude this, the return value is queryset type.

Book.objects.exclude(id=6)

Id return all objects 6 is not equal.

exclude can also call on the basis of queryset

Book.objects.all().exclude(id=6)
order_by(field)

queryset type of data call, sort the query result, the default is ascending order according to the id, returns the value or type queryset:

models.Book.objects.all().order_by('price','id')

Price write directly, default is arranged in ascending order of price. If you want to descending order field, you write a minus sign on the line, that is order_by('-price'). order_by('price','id')Condition is multiple sort in ascending order. Price performed, the same data. Price, according to the ascending id

reverse()

queryset type of data to call, reverse the order of the query results, the return value type or queryset

count()

queryset type of data call, return query the database to match the number of objects (QuerySet) of.

ret = models.UserInfo.objects.all().count()
first()

queryset type of data call, returns the first record

Book.objects.all()[0] = Book.objects.all().first()

The resulting model is an object, not queryset

last()

queryset type of data call, returns the last record, and a method using firstthe same.

exists()

queryset type of data to call, if the QuerySet contains data, returns True, otherwise False.

Empty queryset types of data are also Boolean True and False, but sometimes not suitable for direct use it to determine which database data is not there. If you have a lot of data, you use it to judge, then you need to check out all the data, efficiency is bad. With the count or exits, such as:

all_books = models.Book.objects.all().exists()

SQL statement is translated into:

SELECT (1) AS a FROM app01_book LIMIT 1

Is through the limit 1, take a look at the data is not there, it is a lot higher efficiency.

values(*field)

With more. queryset type of data call, return a ValueQuerySet-- a special QuerySet. After running the instance of the object is not to get a series of model, but a dictionary can be iterative sequence. Queryset as long as the return type, you can continue the chain call other methods to find queryset type, other methods are the same.

queryset call:

ret = models.UserInfo.objects.all().values('age','username')

objects to call - the value of all the data were:

ret = models.UserInfo.objects.values('age','username')
values_list(*field)

It values()is very similar, it returns a tuple sequence, return values is a sequence of dictionary

distinct()

queryset types of data and values ​​obtained values_list to call, discarding duplicates from the returned results records

ret = models.UserInfo.objects.all().values('age','username').distinct()
ret = models.UserInfo.objects.values('age','username').distinct()

MRO create a format time

When you create, add date way of field data

models.Book.objects.create(
    publish_date = "2019-08-01",    # 字符串
    # publish_date = datetime.datetime.now(), 时间日期数据
)

update 和 delete

When the update update data, only queryset types of data:

models.Book.objects.filter(id=2).update(username='xxx')  #update的调用者是queryset类型数据

When delete delete data, you can use queryset types of data, you can use direct data objects:

models.Book.objects.filter(id=2).delete()
models.Book.objects.get(id=2).delete()

Exercise

  1. Press inquiries certain books ever published price is greater than 200
  2. Discover all books py names beginning with August 2017 published
  3. Check rates for the 50,100 or 150 names of all the books and their publishers name
  4. All book titles for price between 100-200 and its price
  5. Search People's Publishing House published books price (high to low sorting, de-emphasis)

Guess you like

Origin www.cnblogs.com/shuoliuchina/p/12521553.html