一个比较全面的DJANGO_REST_FRAMEWORK的CASE

验证啊,过滤啊,hypermedia as the engine of ap‐plication state (HATEOAS)啊都有的。

urls.py

__author__ = ‘sahara‘
from rest_framework.routers import DefaultRouter
from . import views

router = DefaultRouter()
router.register(r‘sprints‘, views.SprintViewSet)
router.register(r‘tasks‘, views.TaskViewSet)
router.register(r‘users‘, views.UserViewset)

models.py

# Create your models here.

from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.conf import settings

class Sprint(models.Model):
    """Development iteration period."""
    name = models.CharField(max_length=100, blank=True, default=‘‘)
    description = models.TextField(blank=True, default=‘‘)
    end = models.DateField(unique=True)

    def __unicode__(self):
        return self.name or _(‘Sprint ending %s‘) % self.end

class Task(models.Model):
    """Unit of work to be done for the sprint."""
    STATUS_TODO = 1
    STATUS_IN_PROGRESS = 2
    STATUS_TESTING = 3
    STATUS_DONE = 4
    STATUS_CHOICES = (
        (STATUS_TODO, _(‘Not Started‘)),
        (STATUS_IN_PROGRESS, _(‘In Progress‘)),
        (STATUS_TESTING, _(‘Testing‘)),
        (STATUS_DONE, _(‘Done‘)),
    )
    name = models.CharField(max_length=100)
    description = models.TextField(blank=True, default=‘‘)
    sprint = models.ForeignKey(Sprint, blank=True, null=True)
    status = models.SmallIntegerField(choices=STATUS_CHOICES, default=STATUS_TODO)
    order = models.SmallIntegerField(default=0)
    assigned = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
    started = models.DateField(blank=True, null=True)
    due = models.DateField(blank=True, null=True)
    completed = models.DateField(blank=True, null=True)

    def __unicode__(self):
        return self.name

forms.py

__author__ = ‘sahara‘
import django_filters
from .models import Task, Sprint
from django.contrib.auth import get_user_model

User = get_user_model()

class NullFilter(django_filters.BooleanFilter):
    def filter(self, qs, value):
        if value is not None:
            return qs.filter(**{‘%s__isnull‘ % self.name: value})
        return qs

class TaskFilter(django_filters.FilterSet):
    backlog = NullFilter(name=‘sprint‘)

    class Meta:
        model = Task
        fields = (‘sprint‘, ‘status‘, ‘assigned‘,‘backlog‘, )

    def __init__(self, *args, **kwargs):
        super(TaskFilter, self).__init__(*args, **kwargs)
        self.filters[‘assigned‘].extra.update(
            {‘to_field_name‘: User.USERNAME_FIELD}
        )

class SprintFilter(django_filters.FilterSet):
    end_min = django_filters.DateFilter(name=‘end‘, lookup_type=‘gte‘)
    end_max = django_filters.DateFilter(name=‘end‘, lookup_type=‘lte‘)

    class Meta:
        model = Sprint
        field = (‘end_min‘, ‘end_max‘, )

serializers.py

__author__ = ‘sahara‘
from django.contrib.auth import get_user_model
from rest_framework import serializers
from rest_framework.reverse import reverse
from .models import Sprint, Task
from datetime import date
from django.utils.translation import ugettext_lazy as _

User = get_user_model()

class SprintSerializer(serializers.ModelSerializer):
    links = serializers.SerializerMethodField()

    class Meta:
        model = Sprint
        fields = (‘id‘, ‘name‘, ‘description‘, ‘end‘, ‘links‘, )

    def get_links(self, obj):
        request = self.context[‘request‘]
        return {
            ‘self‘: reverse(‘sprint-detail‘,
                            kwargs={‘pk‘: obj.pk}, request=request),
            ‘tasks‘: reverse(‘task-list‘,
                             request=request) + ‘?sprint={}‘.format(obj.pk),
        }

    def validate_end(self, attrs):
        end_date = attrs
        # new = not self.object
        #changed = self.object and self.object.end != end_date
        if (end_date < date.today()):
            msg = _(‘End date cannot be in the past.‘)
            raise serializers.ValidationError(msg)
        return attrs

class TaskSerializer(serializers.ModelSerializer):
    assigned = serializers.SlugRelatedField(
        slug_field=User.USERNAME_FIELD, required=False, read_only=True, )
    status_display = serializers.SerializerMethodField()
    links = serializers.SerializerMethodField()

    class Meta:
        model = Task
        fields = (‘id‘, ‘name‘, ‘description‘, ‘sprint‘,
                  ‘status‘, ‘status_display‘, ‘order‘,
                  ‘assigned‘, ‘started‘, ‘due‘, ‘completed‘, ‘links‘, )
    def get_status_display(self, obj):
        return obj.get_status_display()
    def get_links(self, obj):
        request = self.context[‘request‘]
        links = {
            ‘self‘: reverse(‘task-detail‘,
                            kwargs={‘pk‘: obj.pk}, request=request),
            ‘sprint‘: None,
            ‘assigned‘: None,
        }
        if obj.sprint_id:
            links[‘sprint‘] = reverse(‘sprint-detail‘,
                                  kwargs={‘pk‘: obj.sprint_id}, request=request)
        if obj.assigned:
            links[‘assigned‘] = reverse(‘user-detail‘,
                                  kwargs={User.USERNAME_FIELD: obj.assigned}, request=request)

        return links

    def validate_sprint(self, attrs):
        sprint = attrs
        if self :
            pass
            ‘‘‘
            if sprint != self.sprint:
                if self.status == Task.STATUS_DONE:
                    msg = _(‘Cannot change the sprint of a completed task.‘)
                    raise serializers.ValidationError(msg)
                if sprint and sprint.end < date.today():
                     msg = _(‘Cannot assign task to passed sprint‘)
                     raise serializers.ValidationError(msg)
            ‘‘‘
        else:
            if sprint and sprint.end < date.today():
                msg = _(‘Cannot add tasks to past sprints.‘)
                raise serializers.ValidationError(msg)
        return attrs

    def validate(self, attrs):
        sprint = attrs.get(‘sprint‘)
        status = int(attrs.get(‘status‘))
        started = attrs.get(‘started‘)
        completed = attrs.get(‘completed‘)
        if not sprint and status != Task.STATUS_TODO:
            msg = _(‘Backlog tasks must have "Not Started" status.‘)
            raise serializers.ValidationError(msg)
        if started and status == Task.STATUS_TODO:
            msg = _(‘Started date cannot be set for not started tasks.‘)
            raise serializers.ValidationError(msg)
        if completed and status != Task.STATUS_DONE:
            msg = _(‘Completed date cannot be set for uncompleted tasks.‘)
            raise serializers.ValidationError(msg)
        return attrs

class UserSerializer(serializers.ModelSerializer):
    full_name = serializers.CharField(source=‘get_full_name‘, read_only=True)
    links = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = (‘id‘, User.USERNAME_FIELD, ‘full_name‘, ‘is_active‘, ‘links‘, )

    def get_links(self, obj):
        request = self.context[‘request‘]
        user_name = obj.get_username()
        return {
            ‘self‘: reverse(‘user-detail‘,
                            kwargs={User.USERNAME_FIELD: user_name}, request=request),
            ‘tasks‘: ‘{}?assigned={}‘.format(
                reverse(‘task-list‘, request=request), user_name),
        }

views.py

from django.contrib.auth import get_user_model
from rest_framework import viewsets, authentication, permissions, filters
from .forms import TaskFilter, SprintFilter
from .models import Sprint, Task
from .serializers import SprintSerializer, TaskSerializer, UserSerializer

# Create your views here.
User = get_user_model()

class DefaultsMixin(object):
    authentication_classes = (
        authentication.BasicAuthentication,
        authentication.TokenAuthentication,
    )
    permission_classes = (
        permissions.IsAuthenticated,
    )
    paginate_by = 25
    paginate_by_param = ‘page_size‘
    max_paginate_by = 100
    filter_backends = (
        filters.DjangoFilterBackend,
        filters.SearchFilter,
        filters.OrderingFilter,
    )

class SprintViewSet(DefaultsMixin, viewsets.ModelViewSet):
    queryset = Sprint.objects.order_by(‘end‘)
    serializer_class = SprintSerializer
    filter_class = SprintFilter
    search_fields = (‘name‘, )
    ordering_fields = (‘end‘, ‘name‘, )

class TaskViewSet(DefaultsMixin, viewsets.ModelViewSet):
    queryset = Task.objects.all()
    serializer_class = TaskSerializer
    filter_class = TaskFilter
    search_fields = (‘name‘, ‘description‘, )
    ordering_fields = (‘name‘, ‘order‘, ‘started‘, ‘due‘, ‘completed‘, )

class UserViewset(DefaultsMixin, viewsets.ReadOnlyModelViewSet):
    lookup_field = User.USERNAME_FIELD
    lookup_url_kwarg = User.USERNAME_FIELD
    queryset = User.objects.order_by(User.USERNAME_FIELD)
    serializer_class = UserSerializer
    search_fields = (User.USERNAME_FIELD, )

截图,注意有相关链接哟。

时间: 2024-10-25 04:47:03

一个比较全面的DJANGO_REST_FRAMEWORK的CASE的相关文章

分享一个比较全面的robots.txt写法

Sitemap: http://www.sdfangyuan.cn/sitemap.xml User-agent: * Disallow: /*?* Disallow: /*#* Disallow: /*%* Disallow: /*^* Disallow: /caches/ Disallow: /phpcms/ Disallow: /install/ Disallow: /phpsso_server/ Disallow: /statics/ Disallow: /api/ Disallow:

最全面的 Android 编码规范指南

最全面的 Android 编码规范指南 本文word文档下载地址:http://pan.baidu.com/s/1bXT75O 1. 前言 这份文档参考了 Google Java 编程风格规范和 Google 官方 Android 编码风格规范.该文档仅供参考,只要形成一个统一的风格,见量知其意就可. 1.1 术语说明 在本文档中,除非另有说明: 术语 class 可表示一个普通类,枚举类,接口或是annotation类型(@interface) 术语 comment 只用来指代实现的注释(im

一篇很全面的freemarker教程

以下内容全部是网上收集: FreeMarker的模板文件并不比HTML页面复杂多少,FreeMarker模板文件主要由如下4个部分组成: 1,文本:直接输出的部分 2,注释:<#-- ... -->格式部分,不会输出 3,插值:即${...}或#{...}格式的部分,将使用数据模型中的部分替代输出 4,FTL指令:FreeMarker指定,和HTML标记类似,名字前加#予以区分,不会输出 下面是一个FreeMarker模板的例子,包含了以上所说的4个部分 <html><br&

[转]一篇很全面的freemarker教程

copy自http://demojava.iteye.com/blog/800204 以下内容全部是网上收集: FreeMarker的模板文件并不比HTML页面复杂多少,FreeMarker模板文件主要由如下4个部分组成: 1,文本:直接输出的部分 2,注释:<#-- ... -->格式部分,不会输出 3,插值:即${...}或#{...}格式的部分,将使用数据模型中的部分替代输出 4,FTL指令:FreeMarker指定,和HTML标记类似,名字前加#予以区分,不会输出 下面是一个FreeM

找到一份比较全面的freemarker语法总结

转载:http://www.havenliu.com/goodarticle/420.html 尊重原版 找到一份比较全面的freemarker语法总结 网上找到的.这份总结很全面.里面还有很详细的列子,一看就明白 语法 FreeMarker的模板文件并不比HTML页面复杂多少,FreeMarker模板文件主要由如下4个部分组成:1. 文本:直接输出的部分2. 注释:<#– … –>格式部分,不会输出3. 插值:即${…}或#{…}格式的部分,将使用数据模型中的部分替代输出4. FTL指令:F

最全面的Android Studio使用教程

最全面的Android Studio使用教程 Android Studio是一套面世时间还不长的IDE(即集成开发环境),目前已经免费向谷歌及Android的开发人员发放.Android Studio以IntelliJ IDEA为基础,后者同样是一套相当出色的Android开发环境.在今天的文章中,我们将共同了解如何创建一个全新Android项目,同时充分发挥 Android Studio所提供的各项功能优势. 1.项目设置 在开始畅游Android Studio的世界之前,大家首先需要点击此处

目前见到的最傻瓜全面的STRUTS入门教程^_^

目前见到的最傻瓜全面的STRUTS入门教程^_^ 一  Jakarta Struts学习之新手上路 Web 应用开发早期曾经是那么的“简单”,那个时候还只是纯HTML页面和浏览器特效而已.由于还涉及不到动态数据操作和商业应用,也就省去了很多麻烦.但是这 样的“简单”只是过眼云烟,如今我们不得不为复杂的基于Web的商业应用开发采用诸多技术. 本文将介绍如何利用Struts进行应用开发的前台整合的开发过程.Struts是一个为开发基于模型(Model)-视图(View)-控制器 (Controlle

最全面的iOS和Mac开源项目和第三方库汇总

UI 下拉刷新 EGOTableViewPullRefresh – 最早的下拉刷新控件. SVPullToRefresh – 下拉刷新控件. MJRefresh – 仅需一行代码就可以为UITableView或者CollectionView加上下拉刷新或者上拉刷新功能.可以自定义上下拉刷新的文字说明.具体使用看“使用方法”. (国人写) XHRefreshControl – XHRefreshControl 是一款高扩展性.低耦合度的下拉刷新.上提加载更多的组件.(国人写) CBStoreHou

超全面的.NET GDI+图形图像编程教程

本篇主题内容是.NET GDI+图形图像编程系列的教程,不要被这个滚动条吓到,为了查找方便,我没有分开写,上面加了目录了,而且很多都是源码和图片~ (*^_^*) 本人也为了学习深刻,另一方面也是为了分享给大家,纯手工码了好几天的字,喜欢的表忘了点赞哦~给点小小的动力~ 目录: <GDI+绘图基础> 1 GDI+概述 2 Graphics类 2.1 Graphics类的方法成员 2.2 引用命名空间 3 常用画图对象 3.1 Pen类 3.2 Color结构 3.3 Font类 3.4 Bru