整个流程完全按照django官网的tutorial进行
今天对django的 Writing your first Django app, part 1 和 Writing your first Django app, part 2 进行了学习,边看文档边自己构建一个django项目
学习过程中的关键点:
1.django使用的数据库自带的sqlite3, 这个在目前项目中的UnitTest时也是使用的自带的sqlite3. 在此之外还可以使用 mysql, PostgreSQL等。在settings文件中对DATABASE的描述中,不同的数据库选用不同的ENGINE, 相对应的NAME( sqlite3使用 本地文件路径,默认路径是os.path.join(BASE_DIR,‘db.sqlite3’)), 使用非sqlite3需要填入USER, PASSWORD, HOST信息
2.django在运行前需要先执行 python manage.py migrate对数据库做初始化操作
3.执行 python manage.py runserver 默认端是8000, 如果需要其他ip对服务进行访问,需要执行 python manage.py runserver 0.0.0.0:8000
4.创建新的app,需要执行python manage.py startapp polls, polls 为app名字,然后在settings.py中的INSTALLED_APPS中添加’polls’在最后,例如
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
)
5.编写app中的models.py文件,定义app中的数据结构,执行
python manage.py makemigrations polls
根据models的变化生成新的migration文件
python manage.py sqlmigrate polls 0001
查询migrate对应的sql操作语句
python manage.py migrate
对数据库进行操作
Migrations are very powerful and let you change your models over time, as you develop your project, without the need to delete your database or tables and make new ones – it specializes in upgrading your database live, without losing data. We’ll cover them in more depth in a later part of the tutorial, but for now, remember the three-step guide to making model changes:
- Change your models (in models.py).
- Run python manage.py makemigrations to create migrations for those changes
- Run python manage.py migrate to apply those changes to the database.
6.创建超级用户
python manage.py createsuperuser
7.注册新的app到admin中
from django.contrib import admin
from .models import Question
admin.site.register(Question)
8.自定义admin中app的格式
from django.contrib import admin
from .models import Question
class QuestionAdmin(admin.ModelAdmin):
fields = ['pub_date', 'question_text']
admin.site.register(Question, QuestionAdmin)
9.admin中对两个model间建立关系
from django.contrib import admin
from .models import Choice, Question
class ChoiceInline(admin.StackedInline):
model = Choice
extra = 3
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline]
admin.site.register(Question, QuestionAdmin)
10.admin中一些小的展示技巧 list_display, list_filter, search_fields, 后续admin专题有更详细的学习