您的位置:首页 > 编程语言 > Go语言

django 中api使用之django-rest-framework

2018-03-20 22:15 615 查看

安装

pip install djangorestframework


serializers

序列化实例(http://www.django-rest-framework.org/api-guide/serializers/)

字段 fields 可以用特定的值,也可以使用 fields = ‘all‘来实例化所有

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', 'groups')

class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = '__all__'


不同的实例化区别

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys.

By default the serializer will include a url field instead of a primary key field.

The url field will be represented using a HyperlinkedIdentityField serializer field, and any relationships on the model will be represented using a HyperlinkedRelatedField serializer field.


tips:当使用HyperlinkedModelSerializer的时候不能使用 fields = ‘all‘,不然会报错,错误信息如下:

ImproperlyConfigured at /ofc/rest_api/custom
Could not resolve URL for hyperlinked relationship using view name "mdcustoms-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field.


view

class CustomDetail(viewsets.ModelViewSet):
queryset = Custom.objects.all().order_by('-date_joined')
serializer_class = CustomSerializer


当然在rest_framework中封装了很多库,比如附待参数generics.ListAPIView,从而使它的写法更简单

class CustomDetail(generics.ListAPIView):
queryset = MdCustoms.objects.all()
serializer_class = MDCustomSerializer

pagination_class = LargeResultsSetPagination
filter_fields = '__all__'


urls

在django2.0版本中

path("rest_api/custom", rest_model.CustomDetail.as_view(), name="rest_mdcustom"),


或者在低版,可以使用类似这种写法

router = 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'))
]


Settings

将rest_framework组建添加到INSTALLED_APPS中:

INSTALLED_APPS = (
...
'rest_framework',
)


支持筛选

# 使支持django-filter 的条件筛选
'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),


分页

参考:http://www.django-rest-framework.org/api-guide/pagination/

分页,可配置的选项比较丰富了,这里使用一个可定义的page方法

在setting里配置

REST_FRAMEWORK = {
# 分页查询
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.CursorPagination',
'PAGE_SIZE': 5,


编写对应的类

class LargeResultsSetPagination(PageNumberPagination):
page_size = 1000
page_size_query_param = 'page_size'
max_page_size = 10000
对应的应用
class CustomDetail(generics.ListAPIView): queryset = MdCustoms.objects.all() serializer_class = MDCustomSerializer pagination_class = LargeResultsSetPagination filter_fields = '__all__'


介绍就到这里了, 用django-rest-framework的相关代码上传到github上,用django-rest-framework写的api查询拉钩上工作信息:https://github.com/huangxifa/job
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: