US IVF birth in the United States fly █ Micro Signal: 138-0226-9370█ █ surrogate pack package gender █ successful surrogacy package of health ██████████████ United States United States IVF birth in hospital
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.
ORM-derived
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 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 "USER": "Database Username" "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
In Django model is the single, definitive source of information for your data. It contains important field and behavior of your stored data. Typically, a model (Model) is mapped to a database table,
basic situation:
- Each model is a Python class that is a subclass of django.db.models.Model.
- Each attribute of the model represents a database field.
- In summary, Django provides you with an automatically generated database access API, for inquiry official document links .
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.
Field collection (for memory)
Custom fields (understanding based)
class UnsignedIntegerField(models.IntegerField): def db_type(self, connection): return 'integer UNSIGNED'
Custom char type field:
class FixedCharField(models.Field): """ char type custom field class """ def __init__(self, max_length, *args, **kwargs): super().__init__(max_length=max_length, *args, **kwargs) self.length = max_length def db_type(self, connection): """ Generating a database table field defines the type of char, length value specified length """ return 'char(%s)' % self.length class Class(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=25) # Above using a custom field type char cname = FixedCharField(max_length=25)
Table structure is created:
The relationship of correspondence with the actual database fields ORM field
Map: '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)',
字段参数
null
用于表示某个字段可以为空。
unique
如果设置为unique=True 则该字段在此表中必须是唯一的 。
db_index
如果db_index=True 则代表着为此字段设置数据库索引。
default
为该字段设置默认值。
时间字段独有
DatetimeField、DateField、TimeField这个三个时间字段,都可以设置如下属性。
auto_now_add
配置auto_now_add=True,创建数据记录的时候会把当前时间添加到数据库。
auto_now
配置上auto_now=True,每次更新数据记录的时候会更新该字段。
关系字段
ForeignKey
外键类型在ORM中用来表示外键关联关系,一般把ForeignKey字段设置在 '一对多'中'多'的一方。
ForeignKey可以和其他表做关联关系同时也可以和自身做关联关系。
字段参数
to
设置要关联的表
to_field
设置要关联的表的字段
related_name
反向操作时,使用的字段名,用于代替原反向查询时的'表名_set'。
例如:
class Classes(models.Model): name = models.CharField(max_length=32) class Student(models.Model): name = models.CharField(max_length=32) theclass = models.ForeignKey(to="Classes")
当我们要查询某个班级关联的所有学生(反向查询)时,我们会这么写:
models.Classes.objects.first().student_set.all()
当我们在ForeignKey字段中添加了参数 related_name 后,
class Student(models.Model): name = models.CharField(max_length=32) theclass = models.ForeignKey(to="Classes", related_name="students")
当我们要查询某个班级关联的所有学生(反向查询)时,我们会这么写:
models.Classes.objects.first().students.all()
related_query_name
反向查询操作时,使用的连接前缀,用于替换表名。
on_delete
当删除关联表中的数据时,当前表与其关联的行的行为。
models.CASCADE
删除关联数据,与之关联也删除
models.DO_NOTHING
删除关联数据,引发错误IntegrityError
models.PROTECT
删除关联数据,引发错误ProtectedError
models.SET_NULL
删除关联数据,与之关联的值设置为null(前提FK字段需要设置为可空)
models.SET_DEFAULT
删除关联数据,与之关联的值设置为默认值(前提FK字段需要设置默认值)
models.SET
删除关联数据,
a. 与之关联的值设置为指定值,设置:models.SET(值)
b. 与之关联的值设置为可执行对象的返回值,设置:models.SET(可执行对象)
def func(): return 10 class MyModel(models.Model): user = models.ForeignKey( to="User", to_field="id", on_delete=models.SET(func) )
db_constraint
是否在数据库中创建外键约束,默认为True。
OneToOneField
一对一字段。
通常一对一字段用来扩展已有字段。
示例
一对一的关联关系多用在当一张表的不同字段查询频次差距过大的情况下,将本可以存储在一张表的字段拆开放置在两张表中,然后将两张表建立一对一的关联关系。
class Author(models.Model): name = models.CharField(max_length=32) info = models.OneToOneField(to='AuthorInfo') class AuthorInfo(models.Model): phone = models.CharField(max_length=11) email = models.EmailField()
字段参数
to
设置要关联的表。
to_field
设置要关联的字段。
on_delete
同ForeignKey字段。
ManyToManyField
用于表示多对多的关联关系。在数据库中通过第三张表来建立关联关系。
字段参数
to
设置要关联的表
related_name
同ForeignKey字段。
related_query_name
同ForeignKey字段。
symmetrical
仅用于多对多自关联时,指定内部是否创建反向操作的字段。默认为True。
举个例子:
class Person(models.Model): name = models.CharField(max_length=16) friends = models.ManyToManyField("self")
此时,person对象就没有person_set属性。
class Person(models.Model): name = models.CharField(max_length=16) friends = models.ManyToManyField("self", symmetrical=False)
此时,person对象现在就可以使用person_set属性进行反向查询。
through
在使用ManyToManyField字段时,Django将自动生成一张表来管理多对多的关联关系。
但我们也可以手动创建第三张表来管理多对多关系,此时就需要通过through来指定第三张表的表名。
through_fields
设置关联的字段。
db_table
默认创建第三张表时,数据库中表的名称。
多对多关联关系的三种方式
方式一:自行创建第三张表
class Book(models.Model): title = models.CharField(max_length=32, verbose_name="书名") class Author(models.Model): name = models.CharField(max_length=32, verbose_name="作者姓名") # 自己创建第三张表,分别通过外键关联书和作者 class Author2Book(models.Model): author = models.ForeignKey(to="Author") book = models.ForeignKey(to="Book") class Meta: unique_together = ("author", "book")
方式二:通过ManyToManyField自动创建第三张表
class Book(models.Model): title = models.CharField(max_length=32, verbose_name="书名") # 通过ORM自带的ManyToManyField自动创建第三张表 class Author(models.Model): name = models.CharField(max_length=32, verbose_name="作者姓名") books = models.ManyToManyField(to="Book", related_name="authors")
方式三:设置ManyTomanyField并指定自行创建的第三张表
class Book(models.Model): title = models.CharField(max_length=32, verbose_name="书名") # 自己创建第三张表,并通过ManyToManyField指定关联 class Author(models.Model): name = models.CharField(max_length=32, verbose_name="作者姓名") books = models.ManyToManyField(to="Book", through="Author2Book", through_fields=("author", "book")) # Through_fields accepts a 2-tuple ( 'field1', 'field2'): # Field1 which is defined name (author) ManyToManyField model foreign keys, field2 is associated with the target model (book) foreign key name. class Author2Book(models.Model): author = models.ForeignKey(to="Author") book = models.ForeignKey(to="Book") class Meta: unique_together = ("author", "book")
note:
When we need to store additional fields in the third relational tables, it is necessary to use a third way.
But when we create a third way to use-many relationship, you can not use the set, add, remove, clear way to manage many relationships, and the need to manage many relationships through third model table .
Meta-information
ORM corresponding class which contains Meta another class, and class encapsulates some Meta information database. The main fields are as follows:
db_table
ORM table name in the database by default app_ class name, you can db_table can override the table name.
index_together
Joint index.
unique_together
United unique index.
ordering
What specify the default sort field.
Only set this property, we query the results can be reverse ().