Home  >  Article  >  Backend Development  >  Django Model operation

Django Model operation

大家讲道理
大家讲道理Original
2017-05-28 09:59:111489browse

1. Database operations

1. Create model table

Basic structure:


##

1 #coding:Utf82 from django.db import models3    4 class userinfo(models.Model):5     #如果没有models.AutoField,默认会创建一个id的自增列6     name = models.CharField(max_length=30)7     email = models.EmailField()8     memo = models.TextField()


##Field explanation:

 1 1、models.AutoField  自增列= int(11) 2   如果没有的话,默认会生成一个名称为 id 的列,如果要显示的自定义一个自增列,必须将给列设置为主键 primary_key=True。 3 2、models.CharField  字符串字段 4   必须 max_length 参数 5 3、models.BooleanField  布尔类型=tinyint(1) 6   不能为空,Blank=True 7 4、models.ComaSeparatedIntegerField  用逗号分割的数字=varchar 8   继承CharField,所以必须 max_lenght 参数 9 5、models.DateField  日期类型 date10   对于参数,auto_now =True则每次更新都会更新这个时间;auto_now_add 则只是第一次创建添加,之后的更新不再改变。11 6、models.DateTimeField  日期类型 datetime12   同DateField的参数13 7、models.Decimal  十进制小数类型= decimal14   必须指定整数位max_digits和小数位decimal_places15 8、models.EmailField  字符串类型(正则表达式邮箱)=varchar16   对字符串进行正则表达式17 9、models.FloatField  浮点类型= double18 10、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   }27 12、models.IPAddressField  字符串类型(ip4正则表达式)28 13、models.GenericIPAddressField  字符串类型(ip4和ip6是可选的)29   参数protocol可以是:both、ipv4、ipv630   验证时,会根据设置报错31 14、models.NullBooleanField  允许为空的布尔类型32 15、models.PositiveIntegerFiel  正Integer33 16、models.PositiveSmallIntegerField  正smallInteger34 17、models.SlugField  减号、下划线、字母、数字35 18、models.SmallIntegerField  数字36   数据库中的字段有:tinyint、smallint、int、bigint37 19、models.TextField  字符串=longtext38 20、models.TimeField  时间 HH:MM[:ss[.uuuuuu]]39 21、models.URLField  字符串,地址正则表达式40 22、models.BinaryField  二进制41 23、models.ImageField图片42 24、models.FilePathField文件


More fields

Parameter explanation:

 1 1、null=True 2   数据库中字段是否可以为空 3 2、blank=True 4   django的Admin中添加数据时是否可允许空值 5 3、primary_key =False 6   主键,对AutoField设置主键后,就会代替原来的自增 id 列 7 4、auto_now 和 auto_now_add 8   auto_now 自动创建---无论添加或修改,都是当前操作的时间 9   auto_now_add 自动创建---永远是创建时的时间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_length17 7、default  默认值18 8、verbose_name  Admin中字段的显示名称19 9、name|db_column  数据库中的字段名称20 10、unique=True  不允许重复21 11、db_index =True  数据库索引22 12、editable=True  在Admin里是否可编辑23 13、error_messages=None  错误提示24 14、auto_created=False  自动创建25 15、help_text  在Admin中提示帮助信息26 16、validators=[]27 17、upload-to


##Parameter explanation

Perform data operations

Check:

models.UserInfo.

object

s.all()


models.UserInfo.objects.all().values('user') #Only Get the user column


models.UserInfo.objects.all().values_

list

('id','user') #Get the id and user column and generate a list


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

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


Added:

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



Delete:

##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 commonly used methods:


##

 1 # 获取个数 2     # 3     # models.Tb1.objects.filter(name='seven').count() 4     # 大于,小于 5     # 6     # models.Tb1.objects.filter(idgt=1)              # 获取id大于1的值 7     # models.Tb1.objects.filter(idlt=10)             # 获取id小于10的值 8     # models.Tb1.objects.filter(idlt=10, idgt=1)   # 获取id大于1 且 小于10的值 9     # in10     #11     # models.Tb1.objects.filter(idin=[11, 22, 33])   # 获取id等于11、22、33的数据12     # models.Tb1.objects.exclude(idin=[11, 22, 33])  # not in13     # contains14     #15     # models.Tb1.objects.filter(namecontains="ven")16     # models.Tb1.objects.filter(nameicontains="ven") # icontains大小写不敏感17     # models.Tb1.objects.exclude(nameicontains="ven")18     # range19     #20     # models.Tb1.objects.filter(idrange=[1, 2])   # 范围bettwen and21     # 其他类似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



2. Detailed explanation of common fields

models.DateTimeField Date type datetime parameters,

auto_now = True: This time will be updated every time it is updatedauto_now_add is only created and added for the first time, and subsequent updates 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')




Modification of the table structure


After the table structure is modified, the data that already exists in the original table will be structurally chaotic. An error will occur when makemigrations updates the table.

Solution:

1, Add added fields, and set the allowed value 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 the admin background to be empty)

2. Set a default value for the newly added field. When generating a table, newly added fields in the previous data 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')

执行makemigrations, migrate 后。老数据会自动应用新增加的规则

 

models.ImageField                        图片

models.GenericIPAddressField      IP


ip = models.GenericIPAddressField(protocol="ipv4",null=True,blank=True)
img = models.ImageField(null=True,blank=True,upload_to="upload")


 


常用参数


选择下拉框 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、连表结构

  • 一对多:models.ForeignKey(其他表)

  • 多对多:models.ManyToManyField(其他表)

  • 一对一:models.OneToOneField(其他表)

 


应用场景:

  • 一对多:当一张表中创建一行数据时,有一个单选的下拉框(可以被重复选择)
    例如:创建用户信息时候,需要选择一个用户类型【普通用户】【金牌用户】【铂金用户】等。

  • 多对多:在某表中创建一行数据是,有一个可以多选的下拉框
    例如:创建用户信息,需要为用户指定多个爱好

  • 一对一:在某表中创建一行数据时,有一个单选的下拉框(下拉框中的内容被用过一次就消失了
    例如:原有含10列数据的一张表保存相关信息,经过一段时间之后,10列无法满足需求,需要为原来的表再添加5列数据

一对多:


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


 这是UserInfo表,可以通过外键,对应到UserType表的ID

 

这是User_Type表的数据

 

多对多:



 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会自动创建第3张关系表,用于对应UserInfo_id 和UserGroup_id

UserInfo表如上所示:

UserGroup表

Django自动生成的对应关系表

userinfo_id = 1 为 Boss,属于1(用户组A)

 

一对一:   (一对多增加了不能重复)


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


 

The above is the detailed content of Django Model operation. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn