开发实践8_project

要求:

使用Restful对Chaos模型作基本操作。

结果:

post 3 组数据后,get 查询如下:

开发实践8_project_第1张图片

put修改后get:

开发实践8_project_第2张图片开发实践8_project_第3张图片

delete pk=3之后get:

开发实践8_project_第4张图片

代码:

 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//', SingleChaos.as_view(), name="detail"),
]

你可能感兴趣的:(python,开发语言)