django开发(二)
1.django数据库操作---model的使用以及django自带的数据api
django中已经做了ORM,表就是一个类class,表中的一个项就是一个对象object,很好用
1.1django自动把每次你对数据库的操作(更改)看成了对model的改变,然后你生成迁移文件,执行迁移更改,使你专注与django而不是sql
上面第一步和第二部之间还要加上一步激活模型,即把model.py所在的app模块注册到settings.py中的installed_app中,体现了可插拔的应用哲学
1.2常用命令
1 python manage.py makemigrations app_name 2 创建迁移文件 3 4 5 python manage.py sqlmigrate app_name 0001 6 0001是是生成的迁移文件名称,可能需要修改 7 查看生成的迁移文件,也就是查看准备执行什么sql语句 8 9 10 python manage.py migrate 11 执行迁移
1.3数据库的shell操作(非常好用)
django的shell进行了ORM很好用,而且数据库中的每一个数据项在django中不仅是一个数据项,他还被映射成一个独立的对象,他还能被加入类方法
ORM-object relation mapping
1 python manage.py shell 2 启动django的shell,自带的shell工具,可以很容易的对数据库进行crud操作,外键检索等等,非常好用,其进行了ORM 3 4 python manage.py dbshell 5 启动对应对应数据库的shell
1 >>> from polls.models import Choice, Question 2 3 # Make sure our __str__() addition worked. 4 >>> Question.objects.all() 5 <QuerySet [<Question: What's up?>]> 6 7 # Django provides a rich database lookup API that's entirely driven by 8 # keyword arguments. 9 >>> Question.objects.filter(id=1) 10 <QuerySet [<Question: What's up?>]> 11 >>> Question.objects.filter(question_text__startswith='What') 12 <QuerySet [<Question: What's up?>]> 13 14 # Get the question that was published this year. 15 >>> from django.utils import timezone 16 >>> current_year = timezone.now().year 17 >>> Question.objects.get(pub_date__year=current_year) 18 <Question: What's up?> 19 20 # Request an ID that doesn't exist, this will raise an exception. 21 >>> Question.objects.get(id=2) 22 Traceback (most recent call last): 23 ... 24 DoesNotExist: Question matching query does not exist. 25 26 # Lookup by a primary key is the most common case, so Django provides a 27 # shortcut for primary-key exact lookups. 28 # The following is identical to Question.objects.get(id=1). 29 >>> Question.objects.get(pk=1) 30 <Question: What's up?> 31 32 # Make sure our custom method worked. 33 >>> q = Question.objects.get(pk=1) 34 >>> q.was_published_recently() 35 True 36 37 # Give the Question a couple of Choices. The create call constructs a new 38 # Choice object, does the INSERT statement, adds the choice to the set 39 # of available choices and returns the new Choice object. Django creates 40 # a set to hold the "other side" of a ForeignKey relation 41 # (e.g. a question's choice) which can be accessed via the API. 42 >>> q = Question.objects.get(pk=1) 43 44 # Display any choices from the related object set -- none so far. 45 >>> q.choice_set.all() 46 <QuerySet []> 47 48 # Create three choices. 49 >>> q.choice_set.create(choice_text='Not much', votes=0) 50 <Choice: Not much> 51 >>> q.choice_set.create(choice_text='The sky', votes=0) 52 <Choice: The sky> 53 >>> c = q.choice_set.create(choice_text='Just hacking again', votes=0) 54 55 # Choice objects have API access to their related Question objects. 56 >>> c.question 57 <Question: What's up?> 58 59 # And vice versa: Question objects get access to Choice objects. 60 >>> q.choice_set.all() 61 <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]> 62 >>> q.choice_set.count() 63 3 64 65 # The API automatically follows relationships as far as you need. 66 # Use double underscores to separate relationships. 67 # This works as many levels deep as you want; there's no limit. 68 # Find all Choices for any question whose pub_date is in this year 69 # (reusing the 'current_year' variable we created above). 70 >>> Choice.objects.filter(question__pub_date__year=current_year) 71 <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]> 72 73 # Let's delete one of the choices. Use delete() for that. 74 >>> c = q.choice_set.filter(choice_text__startswith='Just hacking') 75 >>> c.delete()
1.3常用的ORM之后的函数(在django中的shell运行)
class.objects.get()/filter(xxx__startwith='')/all()
q.choice_set.all()查找外键是q的所有对象
q.choice_set.count()对上一个计数
q.delete()
更多用法见文档
https://docs.djangoproject.com/zh-hans/2.1/ref/models/relations/
https://docs.djangoproject.com/zh-hans/2.1/topics/db/queries/#field-lookups-intro
https://docs.djangoproject.com/zh-hans/2.1/topics/db/queries/
2.django的后台管理页面功能
即在web页面中动态添加、修改、查看数据库中对象和数据,真的很方便很好用
2.1相关的一些命令
1 python manage.py createsuperuser 2 创建管理员账号
3
4 http://127.0.0.1:8000/admin/
5 访问管理界面
2.2但是一定要注意,如果想管理某个app应用模块的model(也就是其中的数据表以及其映射的对象和类),一定要把本模块的model中的class注册到本app模块中的admin.py中
1 from django.contrib import admin 2 from .models import Question 3 4 admin.site.register(Question) 5 6 在本模块的admin.py中添加代码,将需要管理的数据库表注册到admin后台管理中去
2.3调整admin后台管理的显示顺序跟风格
1 from django.contrib import admin 2 3 from .models import Question 4 5 6 class QuestionAdmin(admin.ModelAdmin): 7 fieldsets = [ 8 (None, {'fields': ['question_text']}), 9 ('Date information', {'fields': ['pub_date']}), 10 ] 11 12 admin.site.register(Question, QuestionAdmin)
3.django中的测试
3.1django中的单元测试,在app模块中的test.py中写代码,注意方法名要以test开头,运行测试脚本时候的命令
1 python manage.py test app_name
3.2如果在提交代码的时候自动化的进行测试,那也就是所谓的持续集成----continuous integration
4.静态文件的查找
4.1静态文件目录一般为app_name/static/appname/[type]/xxx.xxx,然后使用 django.contrib.staticfiles
即可让django自动的去查找对应的静态文件,方便管理,但是要在app模块中
4.2django让app有自己的模板有自己的静态文件,再次体现了django的app为单一的模块的思想。但是如果想让django自己去找,那要先把模块注入进来
5.进阶版后台管理界面
5.1可以设置显示数据表class的字段顺序,显示外键、分组显示、还可以自定义admin界面风格等等,这些都是在对应的admin.py中写代码
https://docs.djangoproject.com/zh-hans/2.1/intro/tutorial07/
json、dict、对象之间的互相转化