Django-based Model operation: django-based model operation
I. Database Operations1. Create a model table
Basic Structure:
1 # coding: Utf82 from django. db import models3 4 class userinfo (models. model): 5 # If no models. autoField. By default, an id auto-incrementing column 6 name = models is created. charField (max_length = 30) 7 email = models. emailField () 8 memo = models. textField ()
Field explanation:
1. models. autoField auto-increment column = int (11) 2 if not, a column named id is generated by default. If you want to display a Custom Auto-increment column, you must set the primary key primary_key = True for the column. 3 2. models. charField string field 4 must have the max_length parameter 5 3, models. booleanField boolean type = tinyint (1) 6 cannot be Blank, Blank = True 7 4, models. comaSeparatedIntegerField the number separated by commas = varchar 8 inherits CharField, so max_lenght parameters 9 5 and models are required. dateField date type date10 for parameters, if auto_now = True, this time will be updated each time an update is made; if auto_now_add is created for the first time, the subsequent update will not change. 11 6. models. dateTimeField date type datetime12 is the same as DateField Parameters 13 7. models. decimal type = decimal14 must specify the integer max_digits and decimal_places15 8, models. emailField string type (Regular Expression mailbox) = varchar16 Regular Expression for strings 17 9, models. floatField floating point type = double18 10, models. integerField integer 19 11, models. bigIntegerField long integer 20 integer_field_ranges = {21 'smallintegerfield' :(-32768,32767), 22 'integerfield' :(-example), 23 'bigintegerfield' :(-example ), 24 'positivesmallintegerfield' :( 0, 32767), 25 'positiveintegerfield' :( 0, 2147483647), 26} 27 12, models. IPAddressField string type (ip4 Regular Expression) 28 13. models. genericIPAddressField string type (ip4 and ip6 are optional) 29 when the protocol can be: both, ipv4, ipv630 for verification, the system reports errors 31 14 and models according to the settings. nullBooleanField allows null Boolean types 32 15, models. positiveIntegerFiel is Integer33 16, models. positiveSmallIntegerField is smallInteger34 17, models. slugField minus signs, underscores, letters, numbers 35 18, models. the fields in the SmallIntegerField 36 database include tinyint, smallint, int, bigint37 19, and 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 image 42 24, models. filePathField File
More fields
Parameter description:
1. null = True 2. Can fields in the database be blank? 3. 2. Can a null value be allowed when data is added to the Admin of blank = True 4 django? 5. primary_key = False 6 primary keys?, after the primary key is set for AutoField, it is automatically created instead of the original auto-incrementing id column 7 4, auto_now, and auto_now_add 8 auto_now --- no matter whether you add or modify, is the current operation time 9 auto_now_add automatic creation --- always the creation time 10 5, choices11 GENDER_CHOICE = (12 (u 'M', u 'male '), 13 (u 'F', u 'female '), 14) 15 gender = models. charField (max_length = 2, choices = GENDER_CHOICE) 16 6. max_leng177, default value 18 8, verbose_name Admin field display name 19 9, name | field name 20 10 in db_column database, unique = True, repeated 21 11, db_index = True database index 22 12, editable = True in Admin whether to edit 23 13, error_messages = None error prompt 24 14, auto_created = False automatic creation 25 15, help_text prompt in Admin help information 26 16, validators = [] 27 17, upload-
Parameter description
Perform data operations
Query:
Models. UserInfo. objects. all ()
Models. UserInfo. objects. all (). values ('user') # retrieve only the user Column
Models. UserInfo. objects. all (). values_list ('id', 'user') # retrieve the id and user columns and generate a list
Models. UserInfo. objects. get (id = 1) # retrieve data with id = 1
Models. UserInfo. objects. get (user = 'Rose ') # retrieve data with user = 'Rose'
Add:Models. UserInfo. objects. create (user = 'Rose ', pwd = '123 ')
Or obj = models. userInfo (user = 'Rose ', pwd = '000000') obj. save () or dic = {'user': 'Rose ', 'pwd': '000000'} models. userInfo. objects. create (** dic)
Delete:Models. userInfo. objects. filter (user = 'Rose '). delete (): models. userInfo. objects. filter (user = 'Rose '). update (pwd = '20140901') or obj = models. userInfo. objects. get (user = 'Rose ') obj. pwd = '000000' obj. save () Examples of common methods:
1 # obtain Number 2 #3 # models. tb1.objects. filter (name = 'seven '). count () 4 # greater than, less than 5 #6 # models. tb1.objects. filter (id _ gt = 1) # Get the value of id greater than 1 7 # models. tb1.objects. filter (id _ lt = 10) # Get the value of id less than 10 8 # models. tb1.objects. filter (id _ lt = 10, id _ gt = 1) # obtain the value of id greater than 1 and less than 10 9 # in10 #11 # models. tb1.objects. filter (id _ in = [11, 22, 33]) # obtain data 12 # models whose id is equal to 11, 22, and 33. tb1.objects. exclude (id _ in = [11, 22, 33]) # not in13 # contains14 #15 # models. tb1.objects. filter (name _ contains = "ven") 16 # models. tb1.objects. filter (name _ icontains = "ven") # icontains case insensitive 17 # models. tb1.objects. exclude (name _ icontains = "ven") 18 # range19 #20 # models. tb1.objects. filter (id _ range = [1, 2]) # range bettwen and21 # other types like 22 #23 # startswith, istartswith, endswith, iendswith, 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') 34 # 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
Ii. Common Fields
Models. DateTimeField date type datetimeParameter, auto_now = True: the time auto_now_add will be updated each time. This is only the first creation and addition, and the subsequent update will not 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')
Modify Table StructureAfter the table structure is modified, the existing data in the original table will be disordered. When the makemigrations table is updated, an error will occur. Solution: 1. Add a new field and set it to null. When a table is generated, the newly added fields of the data are empty. (Null = True: Allow null in the database, and blank = True: Allow null in the admin background) 2. Set a default value for the newly added field. When a table is generated, the default value is applied to the newly added field of the previous data.
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')
Run makemigrations. Old data will automatically apply new rules
Models. ImageField Image
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 choices from the drop-down list
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. Table Connection Structure
- One-to-multiple: models. ForeignKey (other tables)
- Many-to-many: models. ManyToManyField (other tables)
- One-to-one: models. OneToOneField (other tables)
Application scenarios:
- One-to-multiple: When a table creates a row of data, there is a single-choice drop-down box (which can be selected repeatedly)
For example, when creating user information, you need to select a user type [common user] [gold user] [platinum user.
- Many-to-many: Create a row of data in a table. There is a drop-down box that can be selected multiple times.
For example, to create user information, you must specify multiple interests for the user.
- One-to-one: when creating a data row in a table, there is a single-choice drop-down box (the content in the drop-down box disappears once it is used
For example, if a table with 10 columns of data is saved, after a period of time, 10 columns cannot meet the requirements, you need to add 5 more columns of data to the original table.
One to multiple:
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)10 email = models.EmailField()11 user_type = models.ForeignKey('UserType')
This is the UserInfo table,You can use a foreign key to correspond to the ID of the UserType table.
This is the data in 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)10 email = models.EmailField()11 user_type = models.ForeignKey('UserType') 12 class UserGroup(models.Model):13 GroupName = models.CharField(max_length=50)14 user = models.ManyToManyField("UserInfo")
Django model will automatically create 3rd Relational Tables for UserInfo_id and UserGroup_id
The UserInfo table is shown as follows:
UserGroup table
Automatically Generated relationship table by Django
Userinfo_id = 1 is Boss, which belongs to 1 (user group)
One-to-one: (one-to-multiple addition cannot be repeated)
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)10 email = models.EmailField()11 user_type = models.ForeignKey('UserType') 12 class UserGroup(models.Model):13 GroupName = models.CharField(max_length=50)14 user = models.ManyToManyField("UserInfo") 15 class Admin(models.Model):16 Address = models.CharField()17 user_info_address = models.OneToOneField('UserInfo')