# Create the project directory
mkdir tutorial
cd tutorial
# Create a virtualenv to isolate our package dependencies locally
virtualenv env
source env/bin/activate # On Windows use `env\Scripts\activate`
# Install Django and Django REST framework into the virtualenv
pip install django
pip install djangorestframework
# Set up a new project with a single application
django-admin.py startproject tutorial . # Note the trailing '.' character
cd tutorial
django-admin.py startapp quickstart
cd ..
上述命令已经完成了django目录初始化
首次同步数据库
python manage.py migrate
在CentOS 5.11环境下,由于使用的是sqlite 3.3.6,则会出现以下报错
如果使用sqlite 3.8.11则不会出现该问题
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/admin/tutorial/env/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
utility.execute()
File "/home/admin/tutorial/env/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/admin/tutorial/env/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/admin/tutorial/env/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/home/admin/tutorial/env/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 83, in handle
executor = MigrationExecutor(connection, self.migration_progress_callback)
File "/home/admin/tutorial/env/lib/python2.7/site-packages/django/db/migrations/executor.py", line 20, in __init__
self.loader = MigrationLoader(self.connection)
File "/home/admin/tutorial/env/lib/python2.7/site-packages/django/db/migrations/loader.py", line 52, in __init__
self.build_graph()
File "/home/admin/tutorial/env/lib/python2.7/site-packages/django/db/migrations/loader.py", line 209, in build_graph
self.applied_migrations = recorder.applied_migrations()
File "/home/admin/tutorial/env/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations
self.ensure_schema()
File "/home/admin/tutorial/env/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 56, in ensure_schema
with self.connection.schema_editor() as editor:
File "/home/admin/tutorial/env/lib/python2.7/site-packages/django/db/backends/sqlite3/schema.py", line 25, in __enter__
self._initial_pragma_fk = c.fetchone()[0]
TypeError: 'NoneType' object has no attribute '__getitem__'
from django.contrib.auth.models import User, Groupfrom rest_framework import serializersclassUserSerializer(serializers.HyperlinkedModelSerializer):classMeta: model = User fields = ('url','username','email','groups')classGroupSerializer(serializers.HyperlinkedModelSerializer):classMeta: model = Group fields = ('url','name')
model = User
NameError: name `User` is not defined
视图
现在定义一些视图,编辑tutorial/quickstart/views.py添加如下
from django.contrib.auth.models import User, Groupfrom rest_framework import viewsetsfrom tutorial.quickstart.serializers import UserSerializer, GroupSerializerclassUserViewSet(viewsets.ModelViewSet):""" API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializerclassGroupViewSet(viewsets.ModelViewSet):""" API endpoint that allows groups to be viewed or edited. """ queryset = Group.objects.all() serializer_class = GroupSerializer
和编写多个视图不同,这里将所有共有特性统一存放到ViewSets的类中。
URLs
编写API URLs,则在 tutorial/urls.py
from django.conf.urls import url, includefrom rest_framework import routersfrom tutorial.quickstart import viewsrouter = routers.DefaultRouter()router.register(r'users', views.UserViewSet)router.register(r'groups', views.GroupViewSet)# Wire up our API using automatic URL routing.# Additionally, we include login URLs for the browsable API.urlpatterns = [url(r'^', include(router.urls)),url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))]