Python3 development of advanced-django Frame takeoff acceleration One (ORM)

Source: Internet
Author: User
Tags postgresql syntax

Read Catalogue

    1. ORM Introduction
    2. The ORM in Django
    3. The model in ORM
    4. ORM's Operation
I. ORM INTRODUCTION 1, ORM Concept

The object-relational mapping (objects relational Mapping, ORM) pattern is a technique to solve the mismatch between object-oriented and relational databases.

In a nutshell, ORM automatically persists objects in a program to a relational database by using metadata that describes the mapping between the object and the database.

ORM acts as a bridge between the business logic layer and the database layer.

2. Orm Origin

Let's start with the O/R. The letter O originates from "object", and R is derived from "relationship" (relational).

In almost all software development processes, objects and relational databases are involved. At the user level and at the business logic level, we are object-oriented.

When the information of the object changes, we need to keep the object's information in the relational database.

Developing in the same way as before, programmers will have a lot of SQL statements in their business logic code to add, read, modify, and delete related data, and the code is often duplicated.

3. ORM's Advantages

The main problem with ORM resolution is the mapping of objects and relationships. It usually corresponds to a class and a table one by one, each instance of the class corresponds to a record in the table, and each property of the class corresponds to each field in the table.

ORM provides a mapping of the database without writing the SQL code directly, manipulating the data from the database just like an object.

Enable software developers to focus on the processing of business logic and improve the efficiency of development.

4. ORM's Disadvantage

The disadvantage of ORM is that it sacrifices the execution efficiency of the program to some extent.

ORM with more SQL statements will not write, relational database related skills degradation ...

5. ORM Summary

ORM is just a tool that can really solve some repetitive, simple work. There is no denying that.

But we cannot expect a tool to solve all problems once and for all, and some special problems need special treatment.

However, in the entire software development process needs special processing should be very few, otherwise the so-called tool also lost its existence significance.

Second, the Ormdjango project in Django uses the MySQL database

1. In the settings.py file of the Django project, configure the database connection information:

DATABASES = {    "default": {        "ENGINE": "Django.db.backends.mysql",  #这里一定要改mysql        "name": "Your database name",  # You need to manually create the database        "user": "Database user name",        "PASSWORD": "Database Password",        "HOST": "Database IP",        "POST": 3306    }}

2. Write the following code in the __init__.py file of the Django project and tell Django to use the Pymysql module to connect to the MySQL database:

Import Pymysqlpymysql.install_as_mysqldb ()

3. Define the class in the app/models.py file ( the class created must inherit models. Model)

It's also important to note that app creation, where the app has a meaningful name, is created in two ways:

One way to create:

Second, create the way command line:

Ps:python3 This command is a two Python version on the machine, if you enter Python directly on a single version!

The following is a successful creation:

4. Perform the action of creating the label

The premise is to define a good class in app/models.py! Also add the name of the app in the configuration file:

Installed_apps = [    'Django.contrib.admin',    'Django.contrib.auth',    'Django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.messages',    'Django.contrib.staticfiles',    'Box',#Add app name]
class User (models. Model):    = models. Autofield (primary_key=true)  #  self-increment primary key    name = models. Charfield (max_length=32)  #  varchar (+)    pwd = models. Charfield (max_length=64)  #  varchar (+)
Create a class

5, start to create data in MySQL, we in pycharm, command line input:

# Register models.py's changes on the laptop 2. Python3 manage.py migrate   # translate the changes into SQL statements, go to database execution

6, the creation of the data, we began to view the data, normal we look at the data Open database, Pycharm also has this feature:

Tick the right-hand side of the Pycharm and click on the database:

Behind is the mouse point is!!!

Third, the model in the ORM

In Django, model is a single, unambiguous source of information about your data. It contains important fields and behaviors for the data you store. Typically, a model maps to a database table,

Basic situation:

    • Each model is a Python class, which is a subclass of Django.db.models.Model.
    • Each property of the model represents a database field.
    • In summary, Django provides you with an automatically generated database access API that details the official documentation links.

Quick Start

The following example defines a person model that contains first_name and last_name.

From django.db import modelsclass person (models. Model):    first_name = models. Charfield (max_length=30)    last_name = models. Charfield (max_length=30)

first_name and last_name are the fields of the model. Each field is specified as a class property, and each property is mapped to a database column.

The person model above will create a database table like this:

CREATE TABLE Myapp_person (    "id" serial NOT NULL PRIMARY KEY,    "first_name" varchar (+) NOT NULL,    "Last_Name" varchar (+) not NULL);

Some notes:

1, the name of the table Myapp_person is automatically generated, if you want to customize the table name, you need to specify the db_table parameter in the model's meta class, it is strongly recommended to use the lowercase table name, especially when using MySQL as the backend database.

2, ID field is added automatically, if you want to specify a custom primary key, just specify Primary_key=true in one of the fields. If Django finds that you have explicitly set Field.primary_key, it will not add an automatic ID column.

3. The Create TABLE SQL in this example is formatted with the PostgreSQL syntax, but it's worth noting that Django generates the appropriate SQL statement based on the database backend type specified in the configuration file.

4. Django supports MySQL5.5 and later.

Four, ORM operation

Basic operations

# Add models. Tb1.objects.create (c1= ' xx ', c2= ' oo ')   # Adds a piece of data that can accept the dictionary type data **kwargsobj = models. TB1 (c1= ' xx ', c2= ' oo ') obj.save () # Check models. Tb1.objects.get (id=123)  # Gets a single piece of data that does not exist then an error (not recommended) models. Tb1.objects.all ()  # gets all models. Tb1.objects.filter (Name= ' seven ')  # Gets the data models for the specified condition. Tb1.objects.exclude (Name= ' seven ')  # removes data for the specified condition # Delete # models. Tb1.objects.filter (Name= ' seven '). Delete ()  # Deletes the data for the specified condition # change models. Tb1.objects.filter (Name= ' seven '). Update (gender= ' 0 ')   # Updates the data for the specified condition and supports **kwargsobj = models. Tb1.objects.get (id=1) obj.c1 = ' 111 ' Obj.save ()   # Modify Single data

Not to be continued ... Specific operation ... Subsequent updates ...

Python3 development of advanced-django Frame takeoff acceleration One (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.