Django 休息框架 api_view 与普通视图 [英] Django rest framework api_view vs normal view

查看:28
本文介绍了Django 休息框架 api_view 与普通视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在到处寻找对此的合理解释,但它们都不够用...你什么时候使用@api_view 装饰器而不是带有 django rest 框架应用

I have been looking everywhere to find a decent explanation for this, and they all come short...When do you use the @api_view decorator rather than a class based view with the django rest framework app

推荐答案

REST Framework 不谈,一般来说,何时使用基于类的视图与基于函数的视图是相同的问题.Django 中的 CBV 很棒、灵活并且可以节省大量样板代码,但有时使用基于函数的视图会更快、更容易、更清晰.用与在 Django 中编写普通视图相同的方法来考虑它.REST Framework 仅支持编写视图代码的两种方法,因为它在 教程.

REST Framework aside, it's the same question of when to use class based views versus function based views in general. CBVs in Django are awesome, flexible and save loads of boilerplate code, but sometimes it's just faster, easier and clearer to use a function based view. Think about it with the same approach you'd take to writing a normal view in Django. REST Framework simply supports both methods of writing view code as it introduces in the tutorial.

通常使用 CBV,除非它妨碍您,然后使用基于函数的视图和装饰器保持简单.在 Django 和 REST 框架中,列表、分页和 CRUD 操作等典型事物的逻辑已经编写好,并且可以以类和 mixin 的形式轻松扩展.如果您的视图逻辑正在做一些明显不同的事情,则基于函数的视图可能是合适的.当然,您可以在您的应用中同时使用这两种方法.

Generally go with a CBV unless it's getting in your way, then keep it simple with a function based view and the decorator. In both Django and the REST Framework, the logic for typical things like lists, pagination and CRUD operations is already written and easily extendable in the form of classes and mixins. If your view logic is doing something notably different, a function based view might be appropriate. And of course you can use both approaches in your app.

这篇关于Django 休息框架 api_view 与普通视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆