1.安装pymysql,mysqlclient,创建项目django-admin startproject django2
2.settings中把DataBase配置换掉
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'djangodb',
'USER': 'root',
'PASSWORD': 'XXX',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
3.(Mysql5.5需要,5.6及以上不要)打开C:\Users\Administrator\AppData\Roaming\Python\Python37\site-packages\django\db\backends\mysql下的base.py,注释掉以下代码
version = Database.version_info
if version < (1, 3, 13):
raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.__version__)
4.创建一个app,python manage.py startapp myapp
在settings.py中添加一下新的app
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp'
]
5.在创建的app下的models.py文件中粘帖
class Person(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=30)
age = models.IntegerField()
def __str__(self):
# 在Python3中使用 def __str__(self):
return self.name
6.(Mysql5.5需要,5.6及以上不要)改一下C:\Users\Administrator\AppData\Roaming\Python\Python37\site-packages\django\db\backends\mysql下的operations.py文件,将原先的decode改为encode
if query is not None:
query = query.decode(errors='replace')
return query
7.更新一下数据库
python manage.py makemigrations
python manage.py migrate
8.安装rest framework
9.在settings加一下
INSTALLED_APPS = [ ... 'rest_framework', ]
10.urls加一下
urlpatterns = [ ... url(r'^api-auth/', include('rest_framework.urls')) ]
11.settings加一下
REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ] }
12.在myapp下创建文件serializers.py,粘帖如下代码:
from rest_framework import serializers
from myapp.models import Person
class PersonSerializer(serializers.ModelSerializer):
# ModelSerializer和Django中ModelForm功能相似
# Serializer和Django中Form功能相似
class Meta:
model = Person
# 和"__all__"等价
fields = ('id', 'name', 'age')
13.在app的views.py中粘帖如下代码:
from rest_framework import viewsets
from myapp.models import Person
from myapp.serializers import PersonSerializer
class PersonViewSet(viewsets.ModelViewSet):
queryset = Person.objects.all()
serializer_class = PersonSerializer
14.在urls.py中添加
router = routers.DefaultRouter() router.register(r'users', UserViewSet) # 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')) ]
15.运行程序