Model operation based on Django

Keywords: Python Django Database less

I. Database Operation

1. Create model tables

Basic structure:

1 #coding:Utf8
2 from django.db import models
3    
4 class userinfo(models.Model):
5     #Without models.AutoField,By default, a id Auto-addition
6     name = models.CharField(max_length=30)
7     email = models.EmailField()
8     memo = models.TextField()

Field Explanation:

 1. models.AutoField Self-adding = int(11)
 2. If not, a column named id will be generated by default. If a custom self-adding column is to be displayed, the column must be set to primary_key=True.
 3.2, models.CharField
 4. Must max_length parameter
 53. models.BooleanField Boolean type = tinyint(1)
 6. Can't be empty, Blank=True
 7. models. ComaSeparated IntegerField
 8. Inherit CharField, so the max_length parameter must be used
 9.5, models.DateField date type date
 10. For parameters, auto_now =True updates this time each time; auto_now_add is only the first creation of the add, and the subsequent updates do not change.
Model. DateTime Field Date type datetime
 12. Parameters with DateField
 Decimal decimal type = decimal
 14. Integer bits max_digits and decimal_places must be specified
 158, models.EmailField string type (regular expression mailbox) = varchar
 16. Regular expressions for Strings
 17 9, models.FloatField Floating point type = double
 1810, models.IntegerField
 19 11, models.BigIntegerField
20   integer_field_ranges ={
21     'SmallIntegerField':(-32768,32767),
22     'IntegerField':(-2147483648,2147483647),
23     'BigIntegerField':(-9223372036854775808,9223372036854775807),
24     'PositiveSmallIntegerField':(0,32767),
25     'PositiveIntegerField':(0,2147483647),
26   }
Model. IPAddressField string type (ip4 regular expression)
2813, models.GenericIPAddressField string types (ip4 and ip6 are optional)
The parameters protocol can be: both, ipv4, ipv6
 30. When validating, errors will be reported based on settings
 3114, models.NullBooleanField
 32 15, models. Positive Integer Fiel
 33 16, models. PositiveSmallInteger Field
 34 17, models.SlugField minus sign, underscore, letter, number
 3518, models.SmallIntegerField
 36. The fields in the database are tinyint, smallint, int, bigint.
3719, models.TextField string = longtext
 3820, models.TimeField Time HH: MM [: SS [. uuuuuuu]]
39 21, models.URLField string, address regular expression
 Model. BinaryField
 41 23, models. Image Field pictures
 4224, models.FilePathField file
More fields

Parametric interpretation:

 1 1,null=True
 2. Can fields in the database be null?
 3 2,blank=True
 4. Can null values be allowed when data is added to django's Admin
 5 3,primary_key =False
 6. Primary key, after setting primary key to AutoField, will replace the original self-adding id column.
 7 4, auto_now and auto_now_add
 8. auto_now Auto Creation - Whether added or modified, it is the time of the current operation
 9. auto_now_add Auto Creation - Always at Creation Time
10 5,choices
11 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_length
 17, default
 18. Display name of field in verbose_name Admin
 19, name|db_column
 20 10, unique=True
 21 11, db_index =True
 22 12, editable=True. Is it editable in Admin
 23 13, error_messages=None
 2414, auto_created=False
 25 15, help_text: Help information in Admin
26 16,validators=[]
27 17,upload-to
Parametric Interpretation

 

Data manipulation

Check:

 

models.UserInfo.objects.all()

 

models.UserInfo.objects.all().values('user') # Take only the user column

 

models.UserInfo.objects.all().values_list('id','user') # takes out the ID and user columns and generates a list

 

models.UserInfo.objects.get(id=1) # fetch data with id=1

 

models.UserInfo.objects.get(user='rose') # fetch user ='rose'data
 

Add:

models.UserInfo.objects.create(user='rose',pwd='123456')
perhaps
obj = models.UserInfo(user='rose',pwd='123456')
obj.save()
perhaps
dic = {'user':'rose','pwd':'123456'}
models.UserInfo.objects.create(**dic)
 

Delete:

models.UserInfo.objects.filter(user='rose').delete()
 

Amend:

models.UserInfo.objects.filter(user='rose').update(pwd='520')
perhaps
obj = models.UserInfo.objects.get(user='rose')
obj.pwd = '520'
obj.save()
 
Examples of common methods are given.
 1 # Get 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 a value with id greater than 1
 7     # models.Tb1.objects.filter(id__lt=10)             # Get a value with id less than 10
 8     # models.Tb1.objects.filter(id__lt=10, id__gt=1)   # Get values with id greater than 1 and less than 10
 9     # in
10     #
11     # models.Tb1.objects.filter(id__in=[11, 22, 33])   # Get data with id equal to 11, 22, 33
12     # models.Tb1.objects.exclude(id__in=[11, 22, 33])  # not in
13     # contains
14     #
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     # range
19     #
20     # models.Tb1.objects.filter(id__range=[1, 2])   # Range bettwen and
21     # Other similar
22     #
23     # startswith,istartswith, endswith, iendswith,
24     # order by
25     #
26     # models.Tb1.objects.filter(name='seven').order_by('id')    # asc
27     # models.Tb1.objects.filter(name='seven').order_by('-id')   # desc
28     # limit ,offset
29     #
30     # models.Tb1.objects.all()[10:20]
31     # group by
32     from django.db.models import Count, Min, Max, Sum
33     # 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 method
 

2. Detailed explanation of common fields

Model. DateTimeField Date type datetime
Parameters,
auto_now = True: This time is updated for each update
auto_now_add is only the first creation of additions, and subsequent updates do 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 models
2 def home(request):
3     models.UserInfo.objects.create(name='yangmv')
4     after = models.UserInfo.objects.all()
5     print after[0].ctime
6     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 structurally chaotic, and when makemigrations update the table, errors will occur.
Solution:
1. The newly added fields are allowed to be null. 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. Set a default value for the newly added field. When a table is generated, the default value is applied to the previously added field of data.
1 from django.db import models
2 
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')

After making migrations, migrate. Old data automatically applies new rules

 

Model. ImageField

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. Concatenated 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 radio 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], etc.
  • Many-to-many: To create a row of data in a table, there is a drop-down box with multiple choices
    For example, to create user information, you need to specify multiple hobbies for users
  • One-to-one: When creating a row of data in a table, there is a radio drop-down box (the contents of the drop-down box disappear once used).
    For example, after a period of time, 10 columns can not meet the needs of the original table containing 10 columns of data to save relevant information, so it is necessary to add 5 columns of data to the original table.

One-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')  

This is the UserInfo table, which corresponds to the ID of the UserType table through the foreign key

 

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)
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")

The Django model automatically creates the third relational table that corresponds to UserInfo_id and UserGroup_id.

The UserInfo table shows as follows:

UserGroup table

Django Automatically Generated Correspondence Table

userinfo_id = 1 is Boss and belongs to 1 (user group A)

 

One-to-one: (One-to-many additions 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')

 

Posted by jfugate on Thu, 27 Jun 2019 11:17:52 -0700