Django的models模型的具体使用
model的常用字段
V=models.CharField(max_length=None[,**options])#varchar V=models.EmailField([max_length=75,**options])#varchar V=models.URLField([verify_exists=True,max_length=200,**options])#varchar V=models.FileField(upload_to=None[,max_length=100,**options])#varchar #upload_to指定保存目录可带格式, V=models.ImageField(upload_to=None[,height_field=None,width_field=None,max_length=100,**options]) V=models.IPAddressField([**options])#varchar V=models.FilePathField(path=None[,match=None,recursive=False,max_length=100,**options])#varchar V=models.SlugField([max_length=50,**options])#varchar,标签,内含索引 V=models.CommaSeparatedIntegerField(max_length=None[,**options])#varchar V=models.IntegerField([**options])#int V=models.PositiveIntegerField([**options])#int正整数 V=models.SmallIntegerField([**options])#smallint V=models.PositiveSmallIntegerField([**options])#smallint正整数 V=models.AutoField(**options)#int;在Django代码内是自增 V=models.DecimalField(max_digits=None,decimal_places=None[,**options])#decimal V=models.FloatField([**options])#real V=models.BooleanField(**options)#boolean或bit V=models.NullBooleanField([**options])#bit字段上可以设置上null值 V=models.DateField([auto_now=False,auto_now_add=False,**options])#date #auto_now最后修改记录的日期;auto_now_add添加记录的日期 V=models.DateTimeField([auto_now=False,auto_now_add=False,**options])#datetime V=models.TimeField([auto_now=False,auto_now_add=False,**options])#time V=models.TextField([**options])#text V=models.XMLField(schema_path=None[,**options])#text ——————————————————————————– V=models.ForeignKey(othermodel[,**options])#外键,关联其它模型,创建关联索引 V=models.ManyToManyField(othermodel[,**options])#多对多,关联其它模型,创建关联表 V=models.OneToOneField(othermodel[,parent_link=False,**options])#一对一,字段关联表属性
经典情景示例
书籍,作者,出版社之间的关系,这里为了便于演示,我们尽量精简了表中的字段,书籍表具有书名,出版社同出版社表建立一对多的关系[foreignkey],一本书可以具有多个作者,又同作者表建立多对多的关系[many-to-many],作者表有名称,年龄,出版社表有出版社名称。
fromdjango.dbimportmodels classPublisher(models.Model): name=models.CharField(max_length=30) def__str__(self): returnself.name classAuthor(models.Model): name=models.CharField(max_length=30) age=models.IntegerField() def__str__(self): returnself.name classBook(models.Model): title=models.CharField(max_length=100) authors=models.ManyToManyField(Author) publisher=models.ForeignKey(Publisher,on_delete=models.CASCADE) def__str__(self): returnself.title
选择对象
获取全体对象
Publisher.objects.all()#获取所有对象
筛选对象
Publisher.objects.filter(name='人们教育出版社')#获取的是一个对象列表 dict={'name':'lemon','age':18} Author.objects.filter(**dict)#列表传参的方法
获取单个对象
Publisher.objects.get(name='机械工业出版社')#找不到会报错!!!
对象排序
Author.objects.order_by("name","-age")#可以按照多个字段排序,-表示逆向排序
连查
Author.objects.filter(name='lemon').order_by('-age')[0]
批量更新
Author.objects.all().update(age='18')
删除对象
Author.objects.filter(name='lemon').delete()
外键和多对多操作
访问外键
Book.objects.get(id=1).publisher#得到书籍的出版社
反向查询
models.Publisher.objects.get(id=1).book_set.all()#反向查询,得到的是一个queryset对象列表
多对多操作
Book.objects.get(id=1).authors.all()#得到queryset对象列表
自定义models方法
classAuthor(models.Model): name=models.CharField(max_length=30) age=models.IntegerField() def__str__(self): returnself.name defstatus(self): ifself.name=='lemon': return'帅哥'
运行结果:
aa=models.Author.objects.get(id=1)
print(aa.status())
———————————————运行结果——————————————————
帅哥
自定义manager管理器
classAuthorManager(models.Manager): defname_count(self,str_name): returnself.filter(name__icontains=str_name).count() classAuthor(models.Model): name=models.CharField(max_length=30) age=models.IntegerField() def__str__(self): returnself.name defstatus(self): ifself.name=='lemon': return'帅哥' #一旦定义了新的管理器,默认管理器需要显示声明出来才可以使用 objects=models.Manger()#默认管理器 object=AuthorManager()#新定义管理器
执行结果:
aa=models.Author.object.name_count('lemon')
print(aa)#——————》2
自定义sql语句
classAuthorManager(models.Manager): defage_stat(self,age_int): cursor=connection.cursor() cursor.execute(""" SELECTNAME FROMapp2_author WHEREage=%s""",[age_int]) #fetchall()返回的是元组的列表 return[row[0]forrowincursor.fetchall()] classAuthor(models.Model): name=models.CharField(max_length=30) age=models.IntegerField() #objects=models.Manager() object=AuthorManager() def__str__(self): returnself.name
执行结果:
aa=models.Author.object.age_stat(18)
print(aa)
-----------------
['lemon','Luouo']
过滤字段发方法
__exact精确等于like'aaa'
__iexact精确等于忽略大小写ilike'aaa'
__contains包含like'%aaa%'
__icontains包含忽略大小写ilike'%aaa%',但是对于sqlite来说,contains的作用效果等同于icontains。
__gt大于
__gte大于等于
__lt小于
__lte小于等于
__in存在于一个list范围内
__startswith以...开头
__istartswith以...开头忽略大小写
__endswith以...结尾
__iendswith以...结尾,忽略大小写
__range在...范围内
__year日期字段的年份
__month日期字段的月份
__day日期字段的日
__isnull=True/False
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。