python rest_framework

1.新建serializer

from django.contrib.auth.models import User,Group
from rest_framework import serializers

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta :
        model = User
        fields = ('url','username','email','group')

class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta :
        model = Group
        fields = ('url','name')

2.view.py配置

from django.contrib.auth.models import User , Group
from rest_framework import viewsets
from User.serializers import UserSerializer , GroupSerializer

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class GroupViewSet(viewsets.ModelViewSet):
    queryset = Group.objects.all()
    serializer_class = GroupSerializer

3url配置

from django.conf.urls import url ,include
from django.contrib import admin
from User import views
from rest_framework import routers

router = routers.DefaultRouter()
router.register(r'users',views.UserViewSet)
router.register(r'group',views.GroupViewSet)

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^',include(router.urls)),
    url(r'^api-auth/',include('rest_framework.urls',namespace='rest_framework'))
]



你可能感兴趣的:(python)