要求:
使用Restful对Chaos模型作基本操作。
结果:
post 3 组数据后,get 查询如下:
put修改后get:
delete pk=3之后get:
代码:
python manage.py startapp pro8_app
注册
总路由 //
path('pro8/', include('pro8_app.urls', namespace="pro8")),
models //
from django.db import models class Chaos(models.Model): nouns = models.CharField(max_length=32, verbose_name="nouns") magnitude = models.IntegerField(verbose_name="mag") @classmethod def get_all(cls): return cls.objects.all() @classmethod def get_one(cls, pk): return cls.objects.get(pk=pk)
serializer //
from rest_framework import serializers from pro8_app.models import Chaos class ChaosSerializer(serializers.ModelSerializer): class Meta: model = Chaos fields = ( "nouns", "magnitude" )
views //
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView from pro8_app.models import Chaos from pro8_app.serializer import ChaosSerializer class ListAllChaosView(ListCreateAPIView): queryset = Chaos.get_all() serializer_class = ChaosSerializer class SingleChaos(RetrieveUpdateDestroyAPIView): queryset = Chaos.get_all() serializer_class = ChaosSerializer lookup_url_kwarg = "nouns"
url //
urlpatterns = [ path('all/', ListAllChaosView.as_view(), name="list"), path('detail/<nouns>/', SingleChaos.as_view(), name="detail"), ]