我在我的webapp中使用了django-rest-framework for api。用django rest框架代替default ORM provided by django好吗?我已经提到了这个post,但仍然很困惑。因为drf要求创建类,我认为最好使用这些代码来处理对象,因为我可以重用代码。
urls.py
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)views.py
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all()
serializer_class = UserSerializerserializers.py
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'groups')如何使用django rest框架在crud中以views.py的方式处理对象?
发布于 2015-08-19 06:41:19
这里有两个层:Model和Model Serializer;Model是底层。
Model。- **A:** create a `view` which, works in the traditional way of rendering the content on the server side and then send back a `POST` request from the client to the view, if you want to edit (i.e. `django-forms`) , or...
- **B:** Setup a `REST API` that lets you fetch and update your database content via `AJAX` request. This is the purpose of an `API`.
Model还是Model Serializer,都必须运行任何逻辑,那么它应该在底层(即Model )上实现。尽管我们没有构建外部应用程序,但我们现在经常使用API是因为它允许更多的交互性和更快的用户界面。当今最流行的前端框架(例如angularjs)都是围绕着使用API的概念构建的。
发布于 2015-08-19 08:40:59
我想在Arnar的出色答案中添加一个可能的场景。
我倾向于使model变粗(许多方法),使DRF serializer & viewset变粗,使视图变细。
https://stackoverflow.com/questions/32086928
复制相似问题