django restframework 简单总结

Posted wspblog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django restframework 简单总结相关的知识,希望对你有一定的参考价值。

官方文档:http://www.django-rest-framework.org/

model.py

class Snippet(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100, blank=True, default='')
    code = models.TextField()
    linenos = models.BooleanField(default=False)
    books = models.ForeignKey('Books', null=True)

    class Meta:
        ordering = ('created',)


class Books(models.Model):
    booktitle = models.CharField(max_length=50)
    snippets = models.ForeignKey('Snippet')

1.序列化

from rest_framework import serializers


class UserSerializer(serializers.ModelSerializer):
    owner = serializers.ReadOnlyField(source="owner.name") # 重写外键字段
    class Meta:
        model = User  #表名称
        fields = ('id', 'username','snippet') # 要序列化的类

2.views

第一种写法:

from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework import generics


class SnippetList(generics.ListCreateAPIView):
    """自动给你写好get和post"""
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer


class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
    """自动给你写好get、put和delete"""
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer

第二种写法:

from rest_framework import viewsets


class SnippetViewSet(viewsets.ModelViewSet):
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer

3.permissions

permissions.py

from rest_framework import permissions


class IsOwnerOrReadOnly(permissions.BasePermission):
    """
    Custom permission to only allow owners of an object to edit it.
    """

    def has_object_permission(self, request, view, obj):
        # Read permissions are allowed to any request,
        # so we'll always allow GET, HEAD or OPTIONS requests.
        if request.method in permissions.SAFE_METHODS:
            return True

        # Write permissions are only allowed to the owner of the snippet.
        return obj.owner == request.user

上面类的意思是只允许创建者去修改


from snippets.permissions import IsOwnerOrReadOnly

在views.py文件里添加
类的属性:
permission_classes = (permissions.IsAuthenticatedOrReadOnly,
                  IsOwnerOrReadOnly,)    

4.Hyperlinked APIs 超链接

外键正向查询:

class SnippetSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Snippet
        fields = ('id', 'title', 'code', 'linenos','books')

urls.py文件里必须设置name参数,否则会报错
 url(r'^snippets/$',views.SnippetList.as_view(),
 name='snippet-list'),
url(r'^snippets/(?P<pk>[0-9]+)/$',views.SnippetDetail.as_view(),
 name='snippet-detail'),
 
反向查询:

class BooksSerializer(serializers.HyperlinkedModelSerializer):

snippets = serializers.HyperlinkedRelatedField(many=True, view_name="snippet-detail",read_only=True)
class Meta:
    model = Books
    fields = ('id', 'booktitle')

以上是关于django restframework 简单总结的主要内容,如果未能解决你的问题,请参考以下文章

django-rest-framework框架总结之View视图之APIViewGenericAPIView视图集ViewSet

Django Rest_Framework的简单介绍

django-restframework 序列化详解

Django Restframework.1

Django restframework

Django——restframework(serializers序列化工具)