One: Orm Relational Object Mapping (object relational Mapping, abbreviation ORM)

Source: Internet
Author: User

In the Days of wolves! Hard to win ten) Django-orm (Create, field type, field parameter) One: ORM Relational Object Mapping (Object Relational Mapping, ORM)

ORM is divided into two types:

DB first creates database tables in the database, etc.
Code first creates a class, then creates a data table from the class, and so on. Django follows the code Frist principle of automatically generating database tables based on classes defined in your code.

II: Django ORM Creation

  1) Create a class

The created class must inherit models. Model, automatically create the table name in the database: App name _ table name, such as: App01_userinfo

    From django.db import Models    # Create your models here.    #表名app01_userinfo    class UserInfo (models. Model):        #默认有id列, or the primary key        Username=models. Charfield (max_length=32)        password=models. Charfield (MAX_LENGTH=32)

  2) Register App

  

    B) Register app        Installed_apps = [            ' django.contrib.admin ',            ' Django.contrib.auth ',            ' Django.contrib.contenttypes ',            ' django.contrib.sessions ',            ' django.contrib.messages ',            ' Django.contrib.staticfiles ',            ' app01 ', #注册APP, above are default values        ]

  3) configuration database, default is Sqllite, can be modified to MySQL, etc.

    A) Sqllte Configuration

DATABASES = {'    default ': {        ' ENGINE ': ' Django.db.backends.sqlite3 ',        ' NAME ': Os.path.join (Base_dir, ' Db.sqlite3 '),    }}

    B) MySQL Configuration

  

DATABASES = {'      default ': {          ' ENGINE ': ' Django.db.backends.mysql ',          ' NAME ': ' MyDatabase ',          ' USER ': ' Mydatabaseuser ',          ' PASSWORD ': ' MyPassword ',          ' HOST ': ' 127.0.0.1 ',          ' PORT ': ' 3306 ',      }  }  

 C) Precautions

Django uses the MySQLdb module link mysql by default
Python3 is using pymysql and is actively modifying to Pymysql: Add the following code to the _init__.py (directory with settings) under project with the same name as the file:

   Import Pymysql   pymysql.install_as_mysqldb ()

  4) Generate Data table

  

        Python manage.py makemigrations  #生成sql        python manage.py migrate  #数据库中生成表等

5) precautions

A) Find the models.py under the app and don't change the name, and Django won't be there.

B) Add Field

  

Class UserInfo (models. Model): Username=models. Charfield (max_length=20) password=models. Charfield (max_length=3)1) field length shortenedPassword=models. Charfield (max_length=32) password=models. Charfield (max_length=30) data lost over length "Alex 1234567 view edit Delete"2) Add field, the field is not allowed to be empty by default. You need to set a default value, or set the field to be emptyClass UserInfo (models. Model): Username=models. Charfield (max_length=20) password=models. Charfield (max_length=3) email=models. Charfield (max_length=30) below is not set Default,null
Python manage.py makemigrations Tip: E:\Django Project exercise \d19new>python manage.py makemigrations You is trying to add a non-nullable field ' e-mail ' to userinfo without a default; We can ' t do that (the database needs something to populate existing rows). Please select a fix:1) provide a one-off the default now ('ll be set to all existing rows with a null value for this COL umn) 2) Quit, and let me add a default in models.py Select a option:fields are not allowed to be empty by default. You need to set a default value, or set the field to be emptyEmail=models. Charfield (Max_length=30,null=true)3) Test=models. Emailfield (max_length=19)#create不会验证, Emailfield is used for Django admin verification, and other things like Urlfield4) Self IDIf you use Autofield (primary_key=true), the default ID is not used
Three: Field type

  

Autofield (Field)-int self-increment column, must be filled in parameter Primary_key=true Bigautofield (Autofield)-bigint self-increment column, must be filled with parameters primary_key= True Note: When the model does not have a self-increment column, a column named ID is automatically created from the Django.db Import models Class UserInfo (models. Model): # automatically creates a column named ID and an integer column with an increment of username = models. Charfield (MAX_LENGTH=32) class Group (models. Model): # Custom Auto-increment nid = models. Autofield (primary_key=true) name = models. Charfield (max_length=32) Smallintegerfield (Integerfield):-Small integer -32768 ~ 32767 Positivesmallintegerfield (Posi Tiveintegerreldbtypemixin, Integerfield)-positive small integer 0 ~ 32767 integerfield (Field)-integer sequence (signed)-2147483648 ~ 2 147483647 Positiveintegerfield (Positiveintegerreldbtypemixin, Integerfield)-positive integer 0 ~ 2147483647 BigIntegerFi Eld (Integerfield):-Long Integer (signed)-9223372036854775808 ~ 9223372036854775807 Custom unsigned integer field class Unsignedintege Rfield (models. Integerfield): def db_type (sElf, Connection): Return ' integer UNSIGNED ' PS: The value returned is the property of the field in the database, the default value for the Django field is: ' 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 ', ' Decimalfie LD ': ' 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 ', ' nullbooleanfield ': ' bool ', ' Onetoonefield ': ' Integer ', ' PositiveintegeRfield ': ' Integer UNSIGNED ', ' positivesmallintegerfield ': ' smallint UNSIGNED ', ' slugfield ': ' varchar  (% (max_length) s) ', ' Smallintegerfield ': ' smallint ', ' TextField ': ' Longtext ', ' Timefield ': ' Time ', ' Uuidfield ': ' char (+) ', Booleanfield (field)-Boolean type Nullbooleanfield (field):-Can    Null Boolean value Charfield (field)-character type-must provide Max_length parameter, Max_length represents character length TextField (field)-Text type Emailfield (Charfield):-String type, Django Admin and Modelform provide authentication mechanism Ipaddressfield (Field)-string type, Django admin to             and modelform provide validation IPV4 mechanism Genericipaddressfield (Field)-string type, Django admin and Modelform provide validation Ipv4 and Ipv6-parameters: protocol, used to specify Ipv4 or Ipv6, ' both ', ' IPv4 ', ' IPv6 ' Unpack_ipv4, if specified as true, enter:: ffff:192.0.2.1, can be resolved to 192.0 .2.1, open thorn function, need protocol= "both" Urlfield (Charfield)-string type, Django admin and Modelform provide authentication URL Slugfield (Charfield )-String type, DjangoThe admin and Modelform provide validation support letters, numbers, underscores, connectors (minus) Commaseparatedintegerfield (Charfield)-string types, which must be formatted as comma-separated numbers Uuidfiel d (field)-String type, Django Admin and Modelform provide validation of UUID format Filepathfield (field)-String, Django Admin and Modelform                Provides the ability to read files under a folder-parameters: path, folder path Match=none, regular match Recursive=false, recursive below folder Allow_files=true, allow file Allow_fol Ders=false, allow folder Filefield (Field)-string, path saved in database, file upload to specified directory-parameter: upload_to = "" Upload        Save path for file storage = None Storage component, default Django.core.files.storage.FileSystemStorage ImageField (Filefield) -String, the path is saved in the database, the file is uploaded to the specified directory-parameter: upload_to = "" The Save path of the uploaded file storage = None Storage component, default Djang   O.core.files.storage.filesystemstorage Width_field=none, upload a picture of the height of the Saved database field name (string) height_field=none  The width of the uploaded image saved database field name (string)  Datetimefield (Datefield)-date + time format Yyyy-mm-dd Hh:mm[:ss[.uuuuuu]][tz] Datefield (datetimecheckmixin, Field) -Date format Yyyy-mm-dd Timefield (datetimecheckmixin, Field)-time format hh:mm[:ss[.uuuuuu]] Durationfield (field)-long integer, time interval, database in accordance with bigint storage, ORM Gets the value of Datetime.timedelta type Floatfield (field)-floating-point type Decimalfield (F        Ield)-10 decimal Places-parameters: max_digits, fractional total length decimal_places, decimal length Binaryfield (Field) -Binary Type field

Note:

Emailfield is used for Django admin authentication.
  
  
Four: Field parameters

Null if the field in the database can be empty db_column the column name of the field in the database db_tablespace

 Default value of the field in the default database Primary_key whether the field in the database is a primary key db_index the field in the database can be indexed unique Whether a field in the database can establish a unique index in the Unique_for_date database whether the field "date" section can establish a unique index unique_for_month the field "month" in the database can establish a unique index UN Ique_for_year whether the field "year" section in the database can establish a unique index verbose_name the field name displayed in Admin blank admin to allow user input as empty ed Itable Admin can edit help_text admin in the field of the prompt information choices Admin Display the contents of the selection box, with the non-volatile data in memory in order to avoid Avoid cross-table operations such as: GF = models. Integerfield (choices=[(0, ' Spike '), (1, ' big Cousin '),],default=1) Error_messages custom error messages (dictionary type) to customize the error message you want to display; Dictionary health: null, blank, invalid, Invalid_choice, unique, and unique_for_date such as: {' null ': ' cannot be empty. ' ' Invalid ': ' Malformed '} validators custom error validation (list type) to customize the desired validation rule from Django.core.validators Imp ORT regexvalidator from django.core.validators import Emailvalidator,urlvalidatoR,decimalvalidator, Maxlengthvalidator,minlengthvalidator,maxvaluevalidator,minvaluevalidator such as: Test = models. Charfield (max_length=32, error_messages={ ' C1 ': ' Priority error message 1 ', ' C2 ': ' Priority error message 2 ', ' C 3 ': ' Priority error message 3 ',}, validators=[ Regexvalidator (regex= ' root_\d+ ', message= ' wrong ', code= ' C1 '), Regexvalidator (regex= ') Root_112233\d+ ', message= ' again wrong ', code= ' C2 '), Emailvalidator (message= ' again wrong ', Code= ' C3 '), ])     Unique_for_date #只对时间做索引
Unique_for_month #只对月分做索引
Unique_for_year
Auto_now #更新时, automatically updated to the current time
Auto_now_add #创建时, automatically generated

Note: Auto_now,auto_now_add,choince uses

Obj=usergroup.objects.filter (id=1). Update (caption= "CEO") #这种方式utime不会更新
    #下面方式更新 utime    obj=usergroup.objects.filter (id=1). Filter ()    obj.caption= "CEO"    Obj.save ()
    Auto_now  #更新时, automatically updated to the current time    Auto_now_add #创建时, automatically generated    class UserGroup (models. Model):        uid=models. Autofield (primary_key=true)        caption=models. Charfield (max_length=32)        ctime=models. Datetimefield (auto_now_add=true,null=true)        utime=models. Datetimefield (auto_now=true,null=true)            obj=usergroup.objects.filter (id=1). Update (caption= "CEO") # This way utime is not updated    #下面方式更新 utime    obj=usergroup.objects.filter (id=1). Filter ()    obj.caption= "CEO"    Obj.save ()    choices, show the dropdown box to Django Admin, avoid querying         user_type_choices= (            (1, "Super User"), (             2, "Normal user"),            (3, "paving user"),            ) #这里是放在内存里面        user_type_id=models. Integerfield (choices=user_type_choices,default=1) #给django admin display drop-down box, avoid the table query

One: Orm Relational Object Mapping (object relational Mapping, abbreviation 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.