django休息框架意味着在视图与视图集之间进行权衡?

Bur*_*ing 9 python django view python-2.7 django-rest-framework

我不知道为什么文档说"这并不意味着它始终是正确的方法.在使用基于类的视图而不是基于函数的视图时,需要考虑类似的一组权衡.使用视图集不太明确而不是单独建立你的观点."

如果我想制作休息api,这类似于ruby-on-rail.我认为这viewsets是一个很好的方法.

有人可以解释一下吗?

文件链接:http: //www.django-rest-framework.org/tutorial/6-viewsets-and-routers/#trade-offs-between-views-vs-viewsets

chu*_*ash 18

使用的主要优势viewsetsviews是简洁.在简单的情况下,您可以使用更少的代码行完成更多工作.

The main disadvantage is that the simplifying assumptions made by viewsets might not always fit the problem space you are working in. As with class-based views in Django, if you try to apply the wrong pattern to a problem you can end up doing more work than you need to to solve a problem.

My personal heuristic is that if I am doing the full set of CRUD operations on a model, I start with viewsets and go from there until I feel the convenience they provide is no longer worth the trouble I am incurring in that specific instance; if I am working with an API endpoint that doesn't map to any models, I'm far more likely to just use a view.

Edit:

In response to your comment, here's an example in code. If I had the following models:

models.py

from django.db import models

class Gizmo(models.Model):
    name = models.CharField(blank=True, null=False)
    last_dusted = models.DateField(null=True)

class Sprocket(models.Model):
    nom = models.CharField(blank=True, null=False)
    last_dusted = models.DateField(null=True)
Run Code Online (Sandbox Code Playgroud)

And I wanted to support the standard HTTP methods with their normal meanings, (namely GET and POST on the list view and GET, PUT, and DELETE on the detail view), I'd create a GizmoViewSet, a SprocketViewSet and call it a day.

Say I also wanted to offer API consumers the ability to dust off all of the gizmos at once. In that case it would make sense to add a dust method to the GizmoViewSet using the @list_route decorator. Suppose that what I really wanted to do though was to offer a single endpoint where that API consumer could dust all the Gizmos and the Sprockets off at once. That doesn't really map very well to either viewset, so I'd add a one off view:

import datetime

from rest_framework.decorators import api_view
from rest_framework.response import Response

from my_app.models import Gizmo, Sprocket

# I used a function-based API view here, but a CBV APIView
# would work just as well. Matter of personal preference...
@api_view
def dust_everything(request):
    today = datetime.date.today()
    Gizmo.objects.all().update(last_dusted=today)
    Sprocket.objects.all().update(last_dusted=today)
    return Response({"status_of_dusting": "successful"})
Run Code Online (Sandbox Code Playgroud)

所以在这种情况下,我不会撕毁我的所有视图并用视图替换它们; 我正在添加一个额外的视图来补充现有的视图集,这是有意义的.

  • 如果我们其他人只有你的理解汤姆.:) (4认同)
  • @BurgerKing"你可以附上一些代码来形容吗?" 你已经对这个问题有一个完全连贯的答案. (2认同)