Django Database ORM Operations-types and parameters of fields

Source: Internet
Author: User
Tags current time

When creating a table from Django's ORM, we need to define our own classes. When defining a class, he has a wide variety of field types, each with its own parameters to configure, and a simple summary below.


First look at the type of field. Although Python offers nearly 20 types, after he transforms into a database table, it is essentially 4 types: string, number, time, and binary.

Autofield (Field)     - int self-increment column, must be filled in with parameter  primary_key=truebigautofield (AutoField)     - bigint self-increment column, must fill in Parameters  primary_key=True     Note: When the model does not have a self-increment column, Automatically creates a column with a column named ID     from django.db import models     Class userinfo (models. Model):        #  automatically creates a column named ID and an integer column that is self-increasing          username = models. Charfield (MAX_LENGTH=32)     class group (models. Model):        #  Custom self-add column          nid = models. Autofield (primary_key=true)         name = models. Charfield (max_length=32) Smallintegerfield (Integerfield):    -  Small integer  -32768 ~  32767positivesmallintegerfield (positiveintegerreldbtypemixin, inTegerfield)     -  Positive Small integer  0 ~ 32767integerfield (Field)      -  integer sequence (signed)  -2147483648 ~ 2147483647positiveintegerfield ( Positiveintegerreldbtypemixin, integerfield)     -  positive integers  0 ~  2147483647BigIntegerField (Integerfield):    -  Long Integer (Signed)  -9223372036854775808  ~ 9223372036854775807 the custom unsigned integer field     class unsignedintegerfield (models. Integerfield):         def db_type (self, connection):             return  ' integer unsigned '      PS:  return value 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 ',         ' 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 (*) ',          ' 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 value type Nullbooleanfield (field):    -  can be null for Boolean charfield (field)      -  character type     -  must provide the Max_length parameter,  max_length represents the character length TextField (Field)      -  text Type Emailfield (Charfield):    -  String type,django  Validation mechanisms are available in admin and Modelform Ipaddressfield (Field)     -  String type,django  The admin and Modelform provide validation  IPV4  mechanism Genericipaddressfield (Field)     -  string type, Django Validation  ipv4 and ipv6    -  parameters are available in  admin and Modelform:         protocol, for specifying 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, opening the Thorn function, need protocol= "both" Urlfield ( Charfield)     -  String type, django  Validation  urlslugfield (Charfield)     -  String type,django  available in admin and Modelform The admin and Modelform provide validation support   letters, numbers, underscores, connectors (minus signs) Commaseparatedintegerfield (Charfield)     -   String type, the format must be comma-delimited number Uuidfield (Field)     -  String type,django  Validation of UUID format in admin and Modelform Filepathfield (Field)     -  string,django  The admin and Modelform provides the ability to read files under Folders     -  parameters:             path,                        Folder path              match=None,                  Regular Matching              Recursive=false,            recursively below the folder             allow_files=true,            Allow files              allow_folders=False,        Allow folder Filefield ( Field)     -  string, the path is saved in the database, the file is uploaded to the specified directory     -  parameter:         upload_to =  ""        save path for uploaded files         storage = None       Storage components, default Django.core.files.storage.FileSystemStorageImageField (Filefield)     -  strings, The path is saved in the database, the file is uploaded to the specified directory     -  parameters:         upload_to  =  ""        save path for uploaded files          storage = none       storage components, default django.core.files.storage.filesystemstorage         width_field=None,    Upload a picture the height of the Saved database field name (string)          height_field=None    upload the width of the 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-ddtimefield (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 Decimalfield (Field)     - 10 decimal      -  parameters:         max_digits, fractional total length          decimal_places, decimal length Binaryfield (Field)     -  binary type 

As in the following example, Charfield is a string, Emailfield is also a string, if open in the database can see the type is varchar. So where is his difference? This is when you manage the database through the Django Admin page, and he automatically does a validation. Example 1

Class UserInfo (models. Model): Username = models. Charfield (max_length=32,blank=true,verbose_name= ' username ') Password = models. Charfield (max_length=60, help_text= ' pwd ') email = models. Charfield (max_length=60) test = models. Emailfield (max_length=19,null=true,error_messages={' invalid ': ' Please enter password '}) User_group = models.        ForeignKey ("UserGroup", to_field= ' uid ') # (Uid,catption,ctime,uptimew) user_type_choices = ((1, ' Super user '), (2, ' normal user '), (3, ' General user '),) user_type_id = models. Integerfield (Choices=user_type_choices,default=1)


Table Structure of the database

650) this.width=650; "src=" https://s5.51cto.com/wyfs02/M02/9B/6B/wKioL1ljGQrjLs7YAADQsqefoLo672.jpg "title=" 9.JPG "Style=" Float:none; "alt=" wkiol1ljgqrjls7yaadqsqefolo672.jpg "/>



Django Admin interface. For the first time, you need to create a superuser with the following Python manage.py Createsuperuser. After login can modify the contents of the table, he will automatically verify the format

650) this.width=650; "src=" https://s3.51cto.com/wyfs02/M02/9B/6C/wKiom1ljGQnybalLAAD4rroV-rw331.jpg "style=" float : none; "title=" 8.JPG "alt=" Wkiom1ljgqnyballaad4rrov-rw331.jpg "/>


Example 2: A field with a time type defined, and I don't want to use an auto-generated ID field, so I need to manually define a self-growing primary key

Class UserGroup (models. Model): uid = models. Autofield (primary_key=true) caption = models. Charfield (max_length=32,unique=true) CTime = models. Datetimefield (Auto_now_add=true, null=true) uptime = models. Datetimefield (Auto_now=true, Null=true)


When defining a field, you need to specify the corresponding parameter in addition to the type. In Django, he provides the following parameters:


null               ->  Whether the DB can be empty default            ->  default value Primary_ key        ->  PRIMARY Key db_column           ->  Column Name db_index            ->  Index Unique             ->   Unique index unique_for_date    ->  indexed by Time unique_for_month   ->   Index by month unique_for_year    ->  indexed by year auto_now            ->  when created, automatically generate time auto_now_add        ->  update is automatically updated to the current time choices            - > django admin in the drop-down box to avoidNon-connected table query blank              ->  Whether the django admin can be empty verbose_name       -> django  Admin Display Field Chinese editable           -> django  Admin can be edited error_messages     ->  error message owes help_text           -> django admin hint validators          -> django form , custom error message (owed)


Please note that in Example 1 the use of choice, the advantage is that the value of not changing, can be stored directly in memory faster, and often changing values, we still need to use the database for multi-table query

This article is from the "Mapo Tofu" blog, please be sure to keep this source http://beanxyz.blog.51cto.com/5570417/1945909

Django Database ORM Operations-types and parameters of fields

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.