初始api
一旦创建数据模型后,Django 自动给予你一套数据库抽象 API,允许你创建,检索,更新和删除对象。
python manage.py help
Available subcommands:
[auth]
changepassword 更改密码
createsuperuser 创建admin超级用户
[contenttypes]
remove_stale_contenttypes
[django]
check
compilemessages
createcachetable 使用设置文件中的信息创建与数据库高速缓存后端一起使用的高速缓存表
dbshell 进入数据库的命令行
diffsettings 显示当前设置文件和Django默认设置(或所指定的另一个设置文件--default)之间的差异
dumpdata 导出数据库数据
flush 清空数据库
inspectdb 让本地的数据库生成models.py内的代码
loaddata 导入数据库数据
makemessages
makemigrations 生成数据库脚本(迁移文件)
migrate 同步数据库 这个和makemigrations是做数据库迁移,每次数据库有更改或者model有更改都需要操作
sendtestemail 向指定的收件人发送测试电子邮件,测试django是否能够发送邮件
shell django的shell命令行
showmigrations 显示项目中的所有数据迁移
sqlflush 打印将对该flush 命令执行的SQL语句
sqlmigrate
sqlsequencereset
squashmigrations
startapp 创建应用
startproject 创建项目
test 对所有已安装的应用程序运行测试
testserver runserver 使用自定义配置运行服务
[sessions]
clearsessions 可以作为cron作业运行,也可以直接清除过期的会话。
[staticfiles]
collectstatic
findstatic
runserver 启动django服务
python manage.py shell
运行代码打开内置python,已设置环境变量:DJANGO_SETTINGS_MODULE
查询
在 SQL 的层面上, QuerySet 对应 SELECT
语句,而*filters*对应类似 WHERE
或 LIMIT
的限制子句。
from polls.models import Question
#查询
Question.objects.all()
Question.objects.values("question_text", "pub_date")
Question.objects.values()
#条件查询 get返回一个对象(只有一个) filter返回一个QuerySet
Question.objects.filter(id=1)
#exact完全匹配 iexact不区分大小写
Question.objects.filter(question_text__exact="What's up")
#contains 不完全匹配
Question.objects.filter(question_text__contains="Who")
##还有{in, gt, gte, lt, lte, startswith, endswith, isnull, regex}
F()
的实例充当查询中的模型字段的引用。这些引用可在查询过滤器中用于在同一模型实例中比较两个不同的字段。
from django.db.models import F
Choice.objects.filter(pk=F("question_id"))
查询 JSONField
......
创建
要创建一个对象,用关键字参数初始化它,然后调用 save() 将其存入数据库。
from polls.models import Choice, Question
from django.utils import timezone
q = Question(question_text="What's new?", pub_date=timezone.now())
q.save()
Choice.objects.create(question=q, choice_text="c")
删除
q.delete()
Question.objects.filter(pub_date__year=2005).delete()
Question.objects.all().delete()
复制
由于继承的工作原理,您必须将 pk 和 id 都设置为 None,并将 _state.add 设置为 True
c = Choice(question=Question.objects.all()[4], choice_text="c")
c.id = None
c.pk = None
c._state.adding = True
c.save()
修改
update()直接在SQL中做更新,不用调用save方法
Question.objects.filter(pk=5).update(question_text="And you?")
update与delete不同的是,更新QuerySet中每一项的数据,需在循环内调用save方法
my_queryset = Question.objects.all().update(question_text="And you?")
for item in my_queryset:
item.save()
关联对象
一对多 ForeignKey
Django 提供了从关联关系 另一边 访问的 API —— 从被关联模型到定义关联关系的模型的连接。
主表为Question,从表为Choice,Choice表中字段question为外键。正向访问:Choice对象访问qusetion字段的数据。反向访问:Question对象访问所有关联Choice对象的列表
正向访问
Choice.objects.get(pk=7).question
反向访问
Question.objects.get(pk=2).choice_set.all()
for i in Question.objects.all():
print(i.choice_set.all())
管理关联对象的其他方法
add(obj1, obj2, ...) create(**kwargs) remove(obj1, obj2, ...) clear() set(sbjs:QuerySet)
多对多 ManyToMany
...
一对一 OneToOne
...