Django REST框架:泛型还是ModelViewSet? [英] Django REST Framework: Generics or ModelViewSets?

查看:47
本文介绍了Django REST框架:泛型还是ModelViewSet?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在REST API中使用了泛型和纯URL,但是现在我遇到了问题:我想要自定义操作,简单的视图来对模型进行处理,例如运行,发布等等。

I use generics and plain urls for my REST API, but now I stuck with problem: I want custom actions, simple views to make some things with my models, like "run", "publish", etc.

ViewSet 提供 action 装饰器来创建自定义动作,但仅在ViewSets还有步进路由器,它使我们能够使用railsish Convention-over-configuration简化一切。

ViewSet gives action decorator to create custom actions, but only in ViewSets, also, there is stepial routers, which gives us ability to simplify everything using railsish convention-over-configuration.

但是我发现 ModelViewSet 具有与泛型相同的功能:完整的CRUD,序列化程序,过滤器,自定义前/后和查询集,因此,它会引发问题:

But I find that ModelViewSet gives us same abilities, as generics: full CRUD, serializers, filters, cusstom pre/post and queryset, so, it leads to question:

为什么 ModelViewSet 具有相同的功能以及更多功能,为什么会有泛型?有什么区别?

Why there is generics if ModelViewSet gives same abilities and more? What a difference?

推荐答案

区别是它们提供了什么方法。

The difference is what methods they offer.

例如:

GenericViewSet 继承自GenericAPIView,但不提供任何基本操作的实现。仅是get_object,get_queryset。

GenericViewSet inherits from GenericAPIView but does not provide any implementations of basic actions. Just only get_object, get_queryset.

ModelViewSet 继承自GenericAPIView,并包含各种操作的实现。换句话说,您不需要执行基本操作,例如列出,检索,创建,更新或销毁。当然,您可以覆盖它们并实现自己的列表或自己的创建方法。

ModelViewSet inherits from GenericAPIView and includes implementations for various actions. In other words you dont need implement basic actions as list, retrieve, create, update or destroy. Of course you can override them and implement your own list or your own create methods.

您可以在API参考部分中了解更多有关此信息的信息:
< a href = http://www.django-rest-framework.org/api-guide/viewsets rel = noreferrer> ModelViewSet

You can read more about it, in the API REFERENCE section: ModelViewSet

这篇关于Django REST框架:泛型还是ModelViewSet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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