The Django model operation

Source: Internet
Author: User

First, the database operation

1. Create Model Table

Basic structure:


1 #coding: Utf82 from django.db import MODELS3    4 class UserInfo (models. Model): 5     #如果没有models. Autofield, the default is to create a self-increment column of ID 6     name = models. Charfield (max_length=30) 7     email = models. Emailfield () 8     memo = models. TextField ()


Field Explanation:


 1 1, models. Autofield self-increment = Int (11) 2 if not, the default is to generate a column named ID, and if you want to display a custom self-increment column, you must set the column as the primary key primary_key=true. 3 2, models. Charfield string Field 4 must max_length parameter 5 3, models. Booleanfield Boolean type =tinyint (1) 6 cannot be empty, Blank=true 7 4, models. Comaseparatedintegerfield a comma-separated number =varchar 8 inherits Charfield, so the parameter 9 5, models must be max_lenght. Datefield Date type Date10 for parameters, Auto_now =true updates the time for each update; Auto_now_add only creates the addition for the first time, and subsequent updates no longer change. 11 6, models. Datetimefield Date type datetime12 with Datefield parameters 13 7, models. Decimal decimal Decimal type = Decimal14 must specify an integer digit max_digits and a decimal place DECIMAL_PLACES15 8, models. Emailfield String type (regular expression mailbox) =varchar16 a regular expression of string 17 9, models. Floatfield floating-point type = Double18 10, models. Integerfield Plastic Surgery 19 11, models. Bigintegerfield integer_field_ranges ={21 ' Smallintegerfield ':( -32768,32767), ' Integerfield ':(-21474836 48,2147483647), Bigintegerfield ':( -9223372036854775808,9223372036854775807), ' Positivesmallintegerfield ':(0 , 32767), "Positiveintegerfield ':(0,2147483647), 26}27 12, models.Ipaddressfield String type (IP4 regular expression) 28 13, models. Genericipaddressfield String Types (IP4 and IP6 are optional) 29 parameters protocol can be: both, IPv4, ipv630 verification, according to the setting error 31 14, models. Nullbooleanfield is allowed to be null for Boolean types 32 15, models. Positiveintegerfiel is Integer33 16, models. Positivesmallintegerfield is SmallInteger34 17, models. Slugfield minus, underscore, letter, number 35 18, models. The fields in the Smallintegerfield number 36 database are: tinyint, smallint, int, bigint37 19, models. TextField string =longtext38 20, models. Timefield time hh:mm[:ss[.uuuuuu]]39 21, models. Urlfield string, address regular expression 40 22, models. Binaryfield Binary 41 23, models. ImageField Pictures 42 24, models. Filepathfield file


More fields

Parameter explanation:


1 1, Null=true 2 whether the field in the database can be empty 3 2, blank=true 4 Django admin can be allowed null value 5 3, Primary_key =false 6 primary key, after setting the primary key to Autofield, Will replace the original self-increment ID column 7 4, Auto_now, and Auto_now_add 8 Auto_now automatically created---whether added or modified, is the time of the current operation 9 Auto_now_add automatically created---is always created at the time of 10 5, Cho ICES11 Gender_choice = (U ' M ', U ' Male '), (U ' F ', U ' Female '), + GENDER = models. Charfield (max_length=2,choices = gender_choice) 16 6, MAX_LENGTH17 7, default defaults 18 8, verbose_name admin field display name 19 9, name Field names in |db_column database 20 10, unique=true not allowed to repeat 21 11, Db_index =true Database index 22 12, editable=true in admin editable 23 13, Error_messa Ges=none Error Tip 24 14, Auto_created=false Auto Create 25 15, Help_text in admin tip help Information 26 16, validators=[]27 17, Upload-to


Parameter interpretation

Operation of the data

Check:

Models. UserInfo.objects.all ()

Models. UserInfo.objects.all (). VALUES (' user ') #只取user列

Models. UserInfo.objects.all (). Values_list (' id ', ' user ') #取出id和user列 and generate a list

Models. UserInfo.objects.get (id=1) #取id =1 data

Models. UserInfo.objects.get (user= ' rose ') #取user = ' Rose ' data


Increase:


Models. UserInfo.objects.create (user= ' Rose ', pwd= ' 123456 ')

Or

obj = models. UserInfo (user= ' Rose ', pwd= ' 123456 ')

Obj.save ()

Or

DIC = {' user ': ' Rose ', ' pwd ': ' 123456 '}

Models. UserInfo.objects.create (**dic)


By deleting:


Models. UserInfo.objects.filter (user= ' Rose '). Delete ()



Change:


Models. UserInfo.objects.filter (user= ' Rose '). Update (pwd= ' 520 ')

Or

obj = models. UserInfo.objects.get (user= ' Rose ')

Obj.pwd = ' 520 '

Obj.save ()

Examples of common methods:



 1 # Gets the number 2 # 3 # models. Tb1.objects.filter (Name= ' seven '). Count () 4 # greater than, less than 5 # 6 # models. Tb1.objects.filter (idgt=1) # Gets the value of ID greater than 1 of 7 # models. Tb1.objects.filter (idlt=10) # Gets the value of ID less than 10 of 8 # models. Tb1.objects.filter (idlt=10, idgt=1) # Gets the value of ID greater than 1 and less than 10 9 # IN10 #11 # models. Tb1.objects.filter (Idin=[11, 22, 33]) # Gets the data with the ID equal to 11, 22, 33, # models. Tb1.objects.exclude (idin=[11, [+]) # not in13 # CONTAINS14 #15 # models. Tb1.objects.filter (namecontains= "Ven") # models. Tb1.objects.filter (nameicontains= "Ven") # Icontains casing not sensitive # models. Tb1.objects.exclude (nameicontains= "Ven") # RANGE19 #20 # models. Tb1.objects.filter (Idrange=[1, 2]) # range Bettwen And21 # other similar #23 # Startswith,istartswith, EndsWith, IENDSW ith,24 # order By25 #26 # models. Tb1.objects.filter (Name= ' seven '). order_by (' id ') # asc27 # models. Tb1.objects.filter (Name= ' seven '). Order_by ('-id ') # deSC28 # limit, offset29 #30 # models. Tb1.objects.all () [10:20]31 # Group by32 from django.db.models import Count, Min, Max, Sum33 # models. Tb1.objects.filter (c1=1). VALUES (' ID '). Annotate (C=count (' num ')) # select "App01_tb1". ID ", COUNT (" App01_tb1 "." Num ") as" C "from" App01_tb1 "WHERE" app01_tb1 "." C1 "= 1 GROUP by" app01_tb1 "." Id


Common methods

Second, detailed characters commonly used paragraph

Models. Datetimefield Date Type DateTime

Parameters

Auto_now = True: The time will be updated for each update

Auto_now_add is only the first time the add is created, and subsequent updates no longer change.



1 class UserInfo (models. Model): 2     name = models. Charfield (max_length=32) 3     CTime = models. Datetimefield (auto_now=true) 4     uptime = models. Datetimefield (Auto_now_add=true)



1 from app01 import models2 def home (Request): 3     models. UserInfo.objects.create (name= ' YANGMV ') 4 after     = models. UserInfo.objects.all () 5     print After[0].ctime6     return render (Request, ' app01/home.html ')


Modification of table structure

When the table structure is modified, the existing data in the original table will be disorganized, and the makemigrations will be wrong when the table is updated.

Workaround:

1, the newly added field, the setting is allowed to be empty. When the table is generated, the newly added fields of the previous data will be empty. (Null=true allows the database to be empty, Blank=true allows admin to be empty in the background)

2. The newly added field, set a default value. When the table is generated, the previous data addition field will apply this default value



1 from django.db import MODELS2 3 # Create your models HERE.4 class UserInfo (models. Model): 5      name = models. Charfield (max_length=32) 6      CTime = models. Datetimefield (auto_now=true) 7      uptime = models. Datetimefield (auto_now_add=true) 8      email = models. Emailfield (max_length=32,null=true) 9      email1 = models. Emailfield (max_length=32,default= ' rose@qq.com ')


Execute makemigrations, migrate after. Old data will automatically apply the new added rules

Models. ImageField Pictures

Models. Genericipaddressfield IP


IP = models. Genericipaddressfield (protocol= "IPv4", null=true,blank=true) img = models. ImageField (null=true,blank=true,upload_to= "upload")



Common parameters


Select the drop-down box choices



1 class UserInfo (models. Model): 2     user_type_list = (3         (1, ' USER '), 4 (2, ' admin '), 5) 6     User_type = models. Integerfield (Choices=user_type_list,default=1)


2. Even table structure

    • One-to-many: models. ForeignKey (Other tables)

    • Many-to-many: models. Manytomanyfield (Other tables)

    • One to one: models. Onetoonefield (Other tables)


Application Scenarios:

    • One-to-many: when a row of data is created in a table, there is a single-selection drop-down box (which can be selected repeatedly)
      For example: When creating user information, you need to select a user type "ordinary user" "Gold user" "Platinum User" and so on.

    • Many-to-many: a row of data is created in a table with a drop-down box that can be selected
      For example, to create user information, you need to assign multiple hobbies to the user

    • One on one: when you create a row of data in a table, there is a single-selection drop-down box (the contents of the drop-down box are used once and disappear.
      For example: A table containing 10 columns of data holds relevant information, after a period of time, 10 columns do not meet the requirements, you need to add 5 columns of data to the original table

Pair of more:


1 from django.db Import models 2  3  4 # Create your models here. 5 class Usertype (models. Model): 6     name = models. Charfield (MAX_LENGTH=50)     7 class UserInfo (models. Model): 8     username = models. Charfield (max_length=50) 9     password = models. Charfield (MAX_LENGTH=50) e-     mail = models. Emailfield ()     User_type = models. ForeignKey (' usertype ')


This is the UserInfo table, which can be obtained by the foreign key, corresponding to the ID of the usertype table

This is the data for the User_type table.

Many-to-many:



1 from django.db Import models 2  3  4 # Create your models here. 5 class Usertype (models. Model): 6     name = models. Charfield (MAX_LENGTH=50)     7 class UserInfo (models. Model): 8     username = models. Charfield (max_length=50) 9     password = models. Charfield (MAX_LENGTH=50) e-     mail = models. Emailfield ()     User_type = models. ForeignKey (' usertype ')-    class UserGroup (models. Model):     GroupName = models. Charfield (max_length=50)     user = models. Manytomanyfield ("UserInfo")


The Django model automatically creates a 3rd relational table that corresponds to userinfo_id and usergroup_id

The UserInfo table looks like this:

UserGroup table

Django Auto-generated corresponding relational table

userinfo_id = 1 is Boss, belongs to 1 (user Group A)

One-to-one: (One-to-many increments cannot be duplicated)


1 from django.db Import models 2  3  4 # Create your models here. 5 class Usertype (models. Model): 6     name = models. Charfield (MAX_LENGTH=50)     7 class UserInfo (models. Model): 8     username = models. Charfield (max_length=50) 9     password = models. Charfield (MAX_LENGTH=50) e-     mail = models. Emailfield ()     User_type = models. ForeignKey (' usertype ')-    class UserGroup (models. Model):     GroupName = models. Charfield (max_length=50)     user = models. Manytomanyfield ("UserInfo") of the    class Admin (models. Model):     Address = models. Charfield ()     user_info_address = models. Onetoonefield (' UserInfo ')


Related Article

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.