django从0开始-02

django中sql语句的用法:

  

1.get
player = models.Player.objects.get(id=1)
返回单个满足条件的对象
2.filter
player = models.Player.objects.filter(id=1)
过滤,返回满足条件的数据
3.count
返回当前查询的总条数
player = models.Player.objects.all().count()
4.first
返回第一个对象
player = models.Player.objects.filter(id=1).first()
5.last
返回最后一个对象
6.exist
判断查询集中是否有数据,如果有则返回True
7.all
返回所有查询出的对象
player = models.Player.objects.all()

  

重点

双下划线起到where的作用
1.filter(title__contains='天')
是否包含,等价于 like '%天%'
SELECT `Team`.`id`, `Team`.`name`, `Team`.`num`, `Team`.`place` FROM `Team` WHERE `Team`.`name` LIKE BINARY %'熊'% 2.startwith,endwith 以什么开头或结尾 exclude(title__endwith='天') 3.year,month,day,week_day,hour,minute,second filter(pub_data__year=2000) 对日期类型的处理 Q对象 django.db.models import Q 可以使用&(and)与,|(or)或,~(not)非 user.objects.filter(Q(pk=6)|Q(pk=10))

  这些方法解决了,自己需要写sql语句的情况。

普通的增删改查

增:
models.Publisher.objects.create(name = new_name)
删:
del_obj = models.Author.objects.get(id)
del_obj.delete()
改:
edit_author_obj = models.Author.objects.get(id = edit_author_id)
edit_author_obj.name = new_author_name
edit_author_obj.save()

  

posted @ 2020-04-11 00:14  是四不是十  阅读(124)  评论(0编辑  收藏  举报