-
学习须知
drf 内置了几种GenericView,其分别继承了通用mixinsView,方便我们开发使用
image.png -
views.py
from rest_framework import generics
from . import models
from .serializers import GoodsSerializer
class GoodsList(generics.ListCreateAPIView):
"""
List all goods, or create a new good.
"""
queryset = models.Goods.objects.all()
serializer_class = GoodsSerializer
class GoodsDetail(generics.RetrieveUpdateDestroyAPIView):
"""
List one good, update the good or delete the good.
"""
queryset = models.Goods.objects.all()
serializer_class = GoodsSerializer
- serializers.py
from rest_framework import serializers
from . import models
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = models.GoodsCategory
fields = "__all__"
class GoodsSerializer(serializers.ModelSerializer):
# 重写外键,序列化输出
category = CategorySerializer()
class Meta:
model = models.Goods
fields = "__all__"
- urls.py
from . import views
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = [
path('goods/',views.GoodsList.as_view(),name='goods_list'),
path('goods/<int:pk>/', views.GoodsDetail.as_view()),
]
urlpatterns = format_suffix_patterns(urlpatterns)
-
展示
image.png
image.png
网友评论