pip install -r requirement.txt
djangorestframework
django-filter
app/urls.py
from rest_framework.routers import SimpleRouter
#獲取路由
router = SimpleRouter()
# 注冊資源疼邀, /app/article/ /app/article/id/
router.register('article', ArticleView)
# 新增路由地址
urlpatterns += router.urls
#app/views.py
class ArticleView(viewsets.GenericViewSet,
mixins.ListModelMixin,
mixins.RetrieveModelMixin,
mixins.DestroyModelMixin,
mixins.CreateModelMixin,
mixins.UpdateModelMixin):
# 獲取資源所對應(yīng)的數(shù)據(jù)信息
queryset = Article.objects.all()
# 序列化
serializer_class = ArticleSerializer
def list(self, request, *args, **kwargs):
queryset = self.get_queryset()
# 將對象轉(zhuǎn)化成json
a = self.get_serializer(queryset, many=True)
# a = [{'id': i.id, 'title':i.title} for i in queryset]
# b = []
# for i in queryset:
# data = {
# 'id': i.id,
# 'title': i.title
# }
# b.append(data)
return Response(a.data)
def retrieve(self, request, *args, **kwargs):
# 獲取主鍵所對應(yīng)的對象信息
instance = self.get_object()
# 序列化
serializer = self.get_serializer(instance)
return Response(serializer.data)
def perform_destroy(self, instance):
# 實現(xiàn)軟刪除
instance.is_delete = 1
instance.save()