创建project
django-admin startproject xxx .
创建app:
python manage.py startapp xxxxx
在setting.py中的installed_app配置里填入注册的应用
INSTALLED_APPS = (
...
'rest_framework',
'snippets',
)
改写models.py
from django.db import models
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles
LEXERS = [item for item in get_all_lexers() if item[1]]
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
STYLE_CHOICES = sorted((item, item) for item in get_all_styles())
class Snippet(models.Model):
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, blank=True, default='')
code = models.TextField()
linenos = models.BooleanField(default=False)
language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)
class Meta:
ordering = ('created',)
执行
python manage.py makemigrations
python manage.py migrate
进行数据迁移
改写好models.py中的模型后,需要在admin.py注册该类,然后才能在admin的管理界面来生成对象数据
生成数据库,
python manage.py makemigrate
python manage.py makemigrations snippets
python manage.py migrate
序列化,通过继承模型序列化类来是实现
class SnippetSerializer(serializers.ModelSerializer):
class Meta:
model = Snippet
fields = ('id', 'title', 'code', 'linenos', 'language', 'style')
编写views.py 视图
然后,在 应用app xxxxx下的urls.py中映射各个视图和路径的关系
snippets/urls.py文件:
from django.conf.urls import url
from snippets import views
urlpatterns = [
url(r'^snippets/$', views.snippet_list),
url(r'^snippets/(?P<pk>[0-9]+)/$', views.snippet_detail),
]
同样的,路由映射也可以这么写:
url(r'^snippets/$', views.SnippetList.as_view()),
在project xxx下将app的urls模块注册
urlpatterns = [
url(r'^', include('snippets.urls')),
]