Object Relational Mapping (ORM)
orm Introduction
orm concept
Object-Relational Mapping (Object Relational Mapping, referred ORM) to solve for the model is a phenomenon occurring not match each object relational database technology.
Simply put, by using the ORM metadata that describes the mapping between the object and the database, the program objects are automatically persisted to a relational database.
ORM between the business logic layer and the database layer acts as a bridge.
From orm
Let's start with O / R. It originated in the letter O "subject" (Object), and R is derived from "relationship" (Relational).
Almost all of the software development process will involve objects and relational databases. At the user level and business logic plane, we are object-oriented. When information is subject to change, we need to target information stored in a relational database.
According to the previous approach to development will be mixed with programmers in their own business logic code many SQL statements to add, read, modify, delete data, and these codes are often repetitive.
orm advantage
The main problem ORM solution is to map objects and relationships. It is usually a class and a correspondence table, a record of each instance of the class corresponding to the table, each field corresponding to each attribute category table.
ORM provides a mapping to the database without writing SQL code directly, just as the operation of the object as the data from the database operations.
Let software developers to focus on business logic processing, improve development efficiency.
orm disadvantage
ORM drawback is that the efficiency of the program will be sacrificed to some extent.
ORM with more SQL statements would not have written, and relational database skills related degradation ...
orm summary
ORM is only a tool, the tool can really solve some repetition, simple labor. This is undeniable.
But we can not expect a tool can solve all the problems once and for all, or some special problems that require special handling.
But the circumstances that require special handling throughout the software development process should all be very little, or so-called tool will be lost meaning of its existence.
In Django ORM
django project using a mysql database
1. In the Django project settings.py file, configure the database connection information:
= DATABASES { " default " : { " ENGINE " : " django.db.backends.mysql " , " NAME " : " Your database name " , # need to manually create the database , " the USER " : " Database user name " , " pASSWORD " : " database password " , " HOST " : " database IP ", "POST": 3306 } }
2. Write the following code in __init__.py file Django project, told Django uses pymysql modules connect to the MySQL database:
import pymysql pymysql.install_as_MySQLdb()
Model
Getting Started
The following example defines a Person model that contains first_name and last_name .
from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30)
first_name and last_name are fields of the model. Each field is specified as a class attribute, each attribute is mapped to a database column.
The above Person model would create a database table like this:
CREATE TABLE myapp_person ( "id" serial NOT NULL PRIMARY KEY, "first_name" varchar(30) NOT NULL, "last_name" varchar(30) NOT NULL );
Some explanation:
- Myapp_person name of the table is automatically generated, if you want to customize the table name, you need to specify Meta class model in db_table parameters, it is strongly recommended to use lowercase table names, especially when using MySQL as the backend database.
- id field is added automatically, if you want to specify a custom primary key, just specify primary_key = True can be in one field. If Django find that you have explicitly set Field.primary_key, it will not automatically add the ID column.
- In this example using PostgreSQL CREATE TABLE SQL syntax formats, but it is worth noting that, Django will be generated according to the corresponding SQL statement specified in the profile of the type of backend database.
- Django supports MySQL5.5 and later.
Django ORM common fields and parameters
Common Fields
Auto Field
int auto increment, must fill in the parameters primary_key = True. When the model, if there is no auto-increment, then automatically creates a column called id columns.
IntegerField
An integral type, in the range -2147483648 to 2147483647.
CharField
Character type, must provide max_length parameters, characters indicating max_length.
DateField
Date field, the date format YYYY-MM-DD, corresponding to the Python datetime.date () instance.
DateTimeField
Time field, the format YYYY-MM-DD HH: MM [: ss [.uuuuuu]] [TZ], corresponding to the Python A datetime.datetime () instance.
Fields Collection
AutoField (Field,) - int auto increment, must fill in the parameters = primary_key True BigAutoField (AutoField) - bigint auto-increment, must fill in the parameters = primary_key True NOTE: When the model, if there is no auto-increment, then automatically creates a column named id column from django.db Import Models class the UserInfo (models.Model): # automatically create a column named id and is an integer column increment username = models.CharField (MAX_LENGTH = 32 ) class Group (Models .model): # Customization additional NID = models.AutoField (primary_key = True) name = models.CharField (MAX_LENGTH = 32 ) SmallIntegerField (IntegerField): - small integer ~ 32767 -32768 PositiveSmallIntegerField (PositiveIntegerRelDbTypeMixin, IntegerField) - a positive integer smaller 32767 ~ 0 IntegerField (Field,) - integer columns (signed) -2147483648 2147483647 ~ PositiveIntegerField (PositiveIntegerRelDbTypeMixin, IntegerField) - ~ 2147483647 positive integers 0 BigIntegerField ( IntegerField): - long integer (signed) -9223372036854775808 ~ 9223372036854775807 BooleanField (Field,) - Boolean type NullBooleanField (Field,): - can be null Boolean as CharField (Field,) - character type - have to provide parameters max_length, max_length characters indicating the TextField (Field,) - text type EmailField (CharField): - string type, Django Admin and authentication mechanisms provided ModelForm IPAddressField (Field,) - string type, Django Admin IPV4 and authentication mechanisms provided ModelForm GenericIPAddressField (Field,) - string type, Django Admin provides authentication and ModelForm Ipv4 and Ipv6 - parameters: Protocol, specifies Ipv4 or Ipv6, ' both ' , " IPv4 " , " IPv6 " unpack_ipv4, if designated as True, the input FFFF ::: 192.0.2.1 time, may be resolved to 192.0.2.1, this opening function, = Protocol " both " URLField (as CharField) - string type, Django Admin ModelForm provide authentication and the URL SlugField (as CharField) -String type, Django ModelForm the Admin provides authentication and support letters, numbers, underscore, hyphen (minus) CommaSeparatedIntegerField (as CharField) - string type, must be a comma-delimited format number UUIDField (Field,) - string type, Django Admin ModelForm and provides verification of the UUID format that FilePathField will (Field,) - string, Django Admin provides functions to read and ModelForm folder file - parameters: path, folder path match = None, regular matching recursive This = False, the following recursive folder allow_files = True, allows files allow_folders = False, allows folder FileField (Field,) - string path stored in the database, upload files to a specified directory - parameters: upload_to = "" path to save the uploaded file Storage = None storage component, the default django.core.files.storage.FileSystemStorage ImageField (FileField) - string path stored in the database, upload files to a specified directory - parameters: upload_to = "" path to save the uploaded file storage = None storage component, the default django.core.files.storage.FileSystemStorage width_field = None, highly upload pictures stored in the database field name (string) height_field =Save the width of a database field names None upload pictures (string) DateTimeField (DateField) - date + time format-MM-YYYY DD HH: MM [: SS [.uuuuuu]] [TZ] DateField (DateTimeCheckMixin, Field,) - Date format-MM-YYYY DD TimeField (DateTimeCheckMixin, Field,) - time format HH: the MM [: SS [.uuuuuu]] DurationField (Field,) - long integer time interval in the database, according to the ORM bigint acquired value stored datetime .timedelta type FloatField (field,) - float DecimalField (field,) - 10 binary decimal - parameters: max_digits, fractional total length decimal_places, fractional bit length BinaryField (field,) - binary type field collection
Custom Fields
class UnsignedIntegerField(models.IntegerField): def db_type(self, connection): return 'integer UNSIGNED'
Custom char type field
class FixedCharField (models.Field): "" " custom field class type char " "" DEF the __init__ (Self, MAX_LENGTH, args *, ** kwargs): Super (). the __init__ (MAX_LENGTH = MAX_LENGTH, * args, ** kwargs) self.length = MAX_LENGTH DEF db_type (Self, Connection): "" " field defines the type of database table generation of char, length value specified by length " "" return ' char (% S) ' % Self. length class class (models.Model): ID = Models.AutoField(primary_key=True) title Models.CharField = (MAX_LENGTH = 25 ) # Using the above-defined fields of type char cname = FixedCharField (max_length = 25)
The relationship of correspondence with the actual database fields ORM field
对应关系: '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) ' , the corresponding relationship
Field parameters
null
Is used to represent a field can be null, the default is not null
unique
If set to the unique = True field in this table must be unique.
db_index
If db_index = True represents the field to database indexes for this purpose.
default
Set the default value for the field
Unique time field
DatetimeField, DateField, TimeField this three time field, the following properties can be set
auto_now_add
Configuring auto_now_add = True, create a data record when the current time will be added to the database.
auto_now
Configuration auto_now = True, each time when updating the data record will update the field.
Relationship field
ForeignKey
Foreign key is used to indicate the type of the foreign key relationship in the ORM, generally one of the fields provided ForeignKey 'many' in 'multiple' of.
ForeignKey can make tables and other relationships at the same time and can also make their own relationships.
Field parameters
to
Set the table to be associated
Subsequent supplements. . .