Django数据库操作语句
增:
1.类实例化
t = Type()
t.label = “散文”
t.description = “1.文学类型的一种。2.指不求形式上整齐,不讲对仗,不押韵的散体文章。”
……
t.save() #保存
2.调用objects的create方法
t = Type.objects.create(label = '古诗', description = '古诗,是中国古代诗歌的一种体裁,又称古体诗或古风')
查:
将查询到的数据放到前端渲染
1.查询
types = Type.objects.all() #查询所有类型
2.传递到前端
return render_to_response("showType.html",locals())
3.在前端页面调用
{% for type in types %}
<p>{{ type.label }}__{{ type.description }}</p>
{% endfor %}
查询语句:
# 按照条件查询
types = Type.objects.filter(label = '小说',id = 3)
# 按照条件查询返回第一条,没有返回None
types = Type.objects.filter(label = "动画片").first()
# 直接获取单条数据,没有报错,get的条件必须唯一,通常用id
types = Type.objects.get(id = 18)
# 查询排序
types = Type.objects.order_by("id")
# 倒序
types = Type.objects.order_by("-id")
# 限制条数
types = Type.objects.filter()[:3]
外键关系(一对多关系)
一个作者对应多篇文章
# 查询一篇文章的作者姓名
name = Article.objects.get(id = 1).author.name
# 查询一个作者的所有文章
articles = Author.objects.get(name = "老舍").article_set.all()
多对多关系
文章和类型
# 查询一篇文章的所有类型
types = Article.objects.get(id = 3).type.all()
# 查询一种类型的所有文章
articles = Type.objects.get(label = "小说").article_set.all()
删:
# 删除单条
t = Type.objects.get(id = 8)
t.delete()
# 删除多条
t = Type.objects.filter(label = "小说")
t.delete()
改:
# 方法一
# 先获取到将修改的那条数据
t = Type.objects.get(id = 3)
# 根据key修改
t.description = "技术来源于生活"
# 保存
t.save()
# 方法二
t = Type.objects.get(id = 3)
t.update(description = "技术高于生活")
# 修改全部
Type.objects.update(description = "我们不一样")
注:在工作中,我们通常用orm的增删改查,但在复杂的逻辑下还是需要用原生的sql进行查询
types = Type.objects.raw("select * from Article_type where id = 3")