一、模型
模型类
from django.db import models
class Book(models.Model):
# 必须要指定最大长度
name = models.CharField(max_length=20, null=False)
author = models.CharField(max_length=20, null=False)
price = models.FloatField(default=0)
手动添加数据
日志
想打印orm对应的sql,在settings中配置:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console':{
'level':'DEBUG',
'class':'logging.StreamHandler',
},
},
'loggers': {
'django.db.backends': {
'handlers': ['console'],
'propagate': True,
'level':'DEBUG',
},
}
}
二、查询
Book.objects.filter
如果没有查询到任何结果,返回空<QuerySet []>
Book.objects.get
如果没有查询到任何结果,报异常Internal Server Error
,返回类型 QuerySet
1.根据主键进行查找
book = Book.objects.get(pk=1)
book = Book.objects.get(id=1)
print(book)
2.根据其他条件来查找
book = Book.objects.get(author='ecithy')
3.查询所有
三、增加
1.create
Book.objects.create(name=name, author=author)
2.save
Book(name=name, author=author).save()
或者
book.name = name
book.author = author
book.price = price
book.save()
四、删除数据
- 删除queryset
Book.objects.filter(pk>1).delete()
- 删除model对象
Book.objects.get(pk=1).delete()
五、修改数据
1.update
更新queryset
Book.objects.filter(id=1).update(name='mufengsir')
2.save
更新model对象
book = Book.objects.get(pk=2)
book.price = 200
book.save()