I've got a simple CBV for all CRUD operations on my model (let's say Book). How should I implement getting object by id and getting a list of all objects? Seems there are many options like:
对于我的模型,我有一个简单的CBV用于所有CRUD操作(比如说Book)。我应该如何通过id实现获取对象并获取所有对象的列表?似乎有很多选择,如:
-
Just create two separate classes Book and BookList.
只需创建两个单独的类Book和BookList。
-
Write some kind of dispatcher inside get method.
在get方法中写一些调度程序。
class BookView(View): def get(self, request, *args, **kwargs): if 'id' in self.kwargs: self.get_object(request, *args, **kwargs) else: self.get_list(request, *args, **kwargs)
-
Override View.dispatch method so that it will call get_list() method if no id provided.
覆盖View.dispatch方法,以便在未提供id时调用get_list()方法。
etc...
So what is best way?
那么最好的方法是什么?
1 个解决方案
#1
0
Best way for crud API's is to use DRF and subclass the generics.ListCreateAPIView
to get a list of all objects or create new object.
crud API的最佳方法是使用DRF并将generics.ListCreateAPIView子类化以获取所有对象的列表或创建新对象。
generics.RetrieveUpdateDestroyAPIView
to get an object by id or to destroy and update the object by id. Like this:
generics.RetrieveUpdateDestroyAPIView通过id获取对象或通过id销毁和更新对象。像这样:
class BookDetail(generics.RetrieveUpdateDestroyAPIView):
"""
Retrieve, update or delete a book instance.
"""
queryset = Book.objects.all()
serializer_class = BookSerializer
You will probably have to create your serializers accordingly.
您可能需要相应地创建序列化程序。
#1
0
Best way for crud API's is to use DRF and subclass the generics.ListCreateAPIView
to get a list of all objects or create new object.
crud API的最佳方法是使用DRF并将generics.ListCreateAPIView子类化以获取所有对象的列表或创建新对象。
generics.RetrieveUpdateDestroyAPIView
to get an object by id or to destroy and update the object by id. Like this:
generics.RetrieveUpdateDestroyAPIView通过id获取对象或通过id销毁和更新对象。像这样:
class BookDetail(generics.RetrieveUpdateDestroyAPIView):
"""
Retrieve, update or delete a book instance.
"""
queryset = Book.objects.all()
serializer_class = BookSerializer
You will probably have to create your serializers accordingly.
您可能需要相应地创建序列化程序。