码迷,mamicode.com
首页 > 其他好文 > 详细

肆拾柒 --- 模型层

时间:2019-10-24 23:31:26      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:注意   str   net   rem   ESS   ast   ever   man   publish   

django模型层

一、单表查询

? 创建一个图书列表:

class Book(models.Model):
    title = models.CharField(max_length=32)
    price = models.DecimalField(max_digital=8,,decimal_places=2)
    publish_dta = models.DateField()

? 增:

models.Bool.objects.create(title = '活着',price = 50,publish_data = '2010.01.01')
book_obj = models.Book(title = '三国',price = 48.8,publish_data = '2018.01.01')
book_obj.save()

? 改:

models.Book.objects.filter(pk=1).update(price = 55.5)
book_obj = models.Book.objects.filter(pk=2).first()
book_obj.title = '三国演义'
book_obj.save()

? 删:

models.Book.objects.filter(pk=1).delete()

1.1 必知必会的十三条

1.1.1 .all()

res = models.Book.objects.all()     #惰性查询
print(res)              # 不调用,不查询,没有输出结果
for i in res:
    print(i.title)          # 有结果

1.1.2 .filter(**kwargs)

res = models.Book.objects.filter(pk=2)  # 参数为过滤条件
print(res)   # 返回queryset对象

1.1.3 .get(**kwargs)

book_obj = models.Book.objects.get(pk=1)  
print(book_obj)   #返回值为空会报错

1.1.4 .first()

res = models.Book.objects.all()
print(res.first())  # 拿到第一个

1.1.5 .last()

res = models.Book.objects.all()
print(res.last())  # 拿到最后一个

1.1.6 .exclude(**kwargs)

res = models.Book.objects.exclude(pk=3).filter(pk=4)
print(res)   # 返回queryset对象

1.1.7 .values(**kwargs)

res = models.Book.objects.values('title')
print(res)    # 返回queryset对象,列表套字典结构

1.1.8 .values_list(**kwargs)

res = models.Book.objects.values_list('title')
print(res)     # 返回queryset对象,列表套元组结构

1.1.9 .count()

res = models.Book.objects.count()
res1 = models.Book.objects.all().count()
print(res,res1)   # 返回统计个数

1.1.10 .distinct()

# 去重:数据必须是一模一样的情况下才能去重
res = models.Book.objects.all().distinct()   
ress = models.Book.objects.values('title').distinct()

1.1.11 order_by(**kwargs)

res = models.Book.Objects.order_by('price') 默认是升序
res1 = models.Book.objects.order_by('-price')

1.1.12 .reverse()

# 前面必须是先结果排序才可以反转
res = models.Book.objects.order_by('price').reverse()

1.1.13 .exists()

res = models.Book>object.filter(pk=1).exists() #没卵用

1.2 双下划线查询

? 查询价格大于200的书:

res = models.Book.objects.filter(price__gt=200)

? 查询价格小于200的书:

res = models.Book.objects.filter(price__lt=200)

? 查询价格大于等于(小于等于)200的书:

res = models.Book.objects.filter(price__gte)
res1 = models.Book.objects.filter(price__lte)

? 查询价格是200或50或100的书:

res = models.Book.objects.filter(priec__in=[200,50,100])

? 价格在200 到700之间的书籍:

res = models.Book.object.filter(price_range=(200,700))

? 查询书名中有p的:

res = models.Book.objects.filter(title__contains='p')#区分大小写
res = models.Book.objects.filter(title__contains='p')#不区分大小写

? 查询书籍中以三开头的:

res = models.Book.objects.filter(title__startswith='三')
res1 = models.Book.objects.filter(title__endswith='P')

? 查询出版日期是2010年的:

res = models.Book.object.filter(publish_date__year='2010')

二、多表查询

? 创建图书、出版社、作者、作者信息多个表:

class Book(models.Model):
    title = models.CharField(max_length=32)
    price = models.DecimalField(max_digits=8,decimal_places=2)
    publish_date = models.DateField(auto_now_add=True)
    publish = models.ForeignKey(tp='Publish')
    authors = models.ManyToManyField(to='Author')
    
    def __ser__(self):
        return self.title
    
class Publish(models.Model):
    name = models.Charfield(max_length=32)
    addr = models.Charfield(max_length=64)
    
    def __str__(self):
        return self.name
    
class Author(models.Model):
    name = models.Charfield(max_length=32)
    age = models.IntegerField()
    author_detail = models.OneToOneField(to='AuthorDetail')
    
    def __str__(self):
        return self.name

class AuthorDetail(models.Model):
    phone = models.BigInterField()
    addr = models.CharField(max_length=64)
    
    def __ser__(self):
        return self.addr

2.1 一对多字段增删改查

? 增:

models.Book.objects.create(title='西游记',price=88,publish_id=1)
# publish_id直接传出版社主键值

publish_obj = models.Publish.object.filter(pk=2).first()
models.Book.objects.creat(title='红楼',price=63,publish=publish_obj)
# publish直接传出版社数据对象

? 删:

models.Pubilsh.objects.filter(pk=2).delete()  #默认是级联更新 级联删除

? 查:

book_obj = models.Book.models.filter(pk=1).first()
res = book_obj.publish
res1 = book_obj.publish_idrrr

2.2 多对多字段增删改查

? 给主键为3的书籍添加两个作者 1 2:

book_obj = models.Book.objects.filter(pk=3).first()
book_obj.authors.add(1,2)

author_obj = models.Author.objects.filter(pk=1).first()
author_obj1 = models.Author.objects.filter(pk=2).first()
book_obj.authors.add(author_obj,author_obj1)

? 修改关系:

book_obj = models.Book.objects.filter(pk=3).first()
book_obj.authors.set([3,])
book_obj.authors.set([1,3])
author_obj = models.Author.objects.filter(pk=1).first()
author_obj1 = models.Author.objects.filter(pk=2).first()
book_obj.authors.set((author_obj,))
book_obj.authors.set((author_obj,author_obj1))

? 删除:

book_obj = models.Book.objects.filter(pk=3).first()
book_obj.authors.remove(2)
book_obj.authors.remove(1,2)

author_obj = models.Author.objects.filter(pk=1).first()
author_obj1 = models.Author.objects.filter(pk=2).first()
book_obj.authors.remove(author_obj)
book_obj.authors.remove(author_obj,author_obj1)

? 清空:

book_obj = models.Book.objects.filter(pk=3).first()
book_obj.authors.clear()

2.3 跨表查询

? 正向查询:外键字段在谁那儿 由谁查谁就是正向;

? 反向查询:谁手里有外键字段 谁就是正向查

? 方法:正向查询按字段,反向查询按表名小写 。

2.3.1 基于对象

? 查询书籍是python入门的出版社名称:

book_obj = models.Book.objects.filter(title='python入门').first()
    # # 正向查询按字段
print(book_obj.publish.name)

? 查询书籍主键是6的作者姓名:

book_obj = models.Book.objects.filter(pk=6).first()
print(book_obj.authors.all())
#正向查询,按字段.当该字段所对应的数据有多个的时候 需要加.all(),否则点外键字段直接就能够拿到数据对象。

? 查询出版社是东方出版社出版过的书籍:

publish_obj = models.Publish.objects.filter(name='东方出版社').first()
print(publish_obj.book_set.all())

? 查询作者是jason写过的所有的书:

author_obj = models.Author.objects.filter(name='jason').first()
print(author_obj.book_set.all())

? 查询手机号是110的作者

author_detail_obj = models.AuthorDetail.objects.filter(phone=110).first()
print(author_detail_obj.author)
print(author_detail_obj.author.name)

? 注意:当查询的结果可以是多个的情况下 需要加_set.all();当查询的结果有且只有一个的情况下 不需要加任何东西 直接表名小写即可。

? 查询书籍是python入门的作者的手机号:

book_obj = models.Book.objects.filter(title='python入门').first()
print(book_obj.authors.all())

2.3.2 基于双下划綫的跨表查询

? 查询书籍是python入门的出版社名称:

#正向
res = models.Book.objects.filter(title='python入门').values('publish__name')
print(res)
    # 反向
res = models.Publish.objects.filter(book__title='python入门').values('name')
print(res)

? 查询作者是jason的手机号码:

# 正向
res1 = models.Author.objects.filter(name='jason').values('author_detail__phone')
print(res1)
# 反向
res = models.AuthorDetail.objects.filter(author__name='jason').values('phone','author__age')
 print(res)

? 查询手机号是120的作者姓名:

res2 = models.AuthorDetail.objects.filter(phone=120).values('author__name')
print(res2)
res = models.Author.objects.filter(author_detail__phone=120).values('name','author_detail__addr')
print(res)

? 查询出版社是东方出版社出版的书籍名称:

res = models.Publish.objects.filter(name='东方出版社').values('book__title','addr')
print(res)

? 查询作者是jason的写过的书的名字和价格:

res = models.Author.objects.filter(name='jason').values('book__title','book__price')
print(res)

? 查询书籍是python入门的作者的手机号:

res = models.Book.objects.filter(title='python入门').values('authors__author_detail__phone')
print(res)

肆拾柒 --- 模型层

标签:注意   str   net   rem   ESS   ast   ever   man   publish   

原文地址:https://www.cnblogs.com/tangceng/p/11735588.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!