1. Install pymysql, mysqlclient, creating a project django-admin startproject django2
2.settings replaced in the configuration DataBase
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'djangodb',
'USER': 'root',
'PASSWORD': 'XXX',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
3. (Mysql5.5 need, not 5.6 and above) to open the C: base.py \ \ \ \ \ \ Python37 \ \ Under Users Administrator AppData Roaming Python site-packages \ django db \ backends \ mysql, and comment out the following code
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. Create an app, python manage.py startapp myapp
5. In models.py paste files in app created
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 needs, 5.6 and above do not) change it C: \ Users \ Administrator \ AppData \ Roaming \ Python \ Python37 \ site-packages \ django \ operations.py file under db \ backends \ mysql, the original the decode changed to encode
if query is not None:
query = query.decode(errors='replace')
return query
7. Update about the database
python manage.py makemigrations
python manage.py migrate
8. Installation rest framework
9. In what settings plus
INSTALLED_APPS = [ ... 'rest_framework', ]
10.urls add about
urlpatterns = [ ... url(r'^api-auth/', include('rest_framework.urls')) ]
11.settings add about
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. serializers.py create a file in myapp, paste the following code:
Import rest_framework serializers from
from myapp.models Import the Person
class PersonSerializer (serializers.ModelSerializer):
# ModelSerializer and functionally similar in Django ModelForm
# Serializer and functionally similar in Django Form
class Meta -:
Model the Person =
# and "__all__" equivalent
fields = ( 'id', 'name', 'age')
13. A paste in the following code in the 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. Add in the 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. Run the program