ORM模型通常放在app的models.py文件中,所以创建该文件,然后需要在settings.py中INSTALLED_APPS添加该app的名称。举个栗子。
我的app名称为front,然后在这个目录下新增一个models.py文件
在文件中添加自己需要的表以及列如,创建一个表book,列:ID,name,author,price
from django.db import models
class Book(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100, null=False)
author = models.CharField(max_length=100, null=False)
price = models.FloatField(null=False, default=0)
在settings.py中INSTALLED_APPS添加该app的名称
需要记住两行指令。
python manage.py makemigrations #来生成迁移脚本文件。
python manage.py migrate #来将迁移脚本文件映射到数据库中
注意:如果输入 Python manage.py makemigrations提示No changes detected,解决方案:
输入这行指令即可:
python manage.py makemigrations --empty yourappname
增:
def index(request):
# 添加数据
book = Book(name='www.lanol.cn', author='Lan', price=100)
book.save()
return HttpResponse('你好')
查:
通过主键:
def index(request):
# 查询数据
# 1,通过主键
book = Book.objects.get(pk=1)
result = f'书本ID:{book.id}
书本名称:{book.name}
书本价格:{book.price}'
return HttpResponse(result)
查询所有数据:
books = Book.objects.all()
查找指定数据:
调用objects的filter方法。
单条件:
books = Book.objects.filter(name='
多条件:
books = Book.objects.filter(name='www.lanol.cn',author='lan')
删除数据:
先get到再删除
book = Book.objects.get(name='www.lanol.cn')
book.delete()
修改数据:
先查找到,再修改,修改后保存。
book = Book.objects.get(name='www.lanol.cn')
book.name = 'lanol.cn'
book.save()
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有