我想将问题详细信息的根分为:问题详细信息,问题更新,问题删除,但我想将针对问题模型的所有操作同时保留在一个视图中。
models.py:
class Question(models.Model):
title = models.CharField(max_length=100)
content = models.CharField(max_length=500, default="Write your question") # HTMLField() look TinyMCE
tags = models.ManyToManyField("Tag")
pub_date = models.DateField(auto_now=False, auto_now_add=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
answers = models.ManyToManyField("Answer")
# comment_cnt = models.IntegerField(default=0)
# like_cnt = models.IntegerField(default=0)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('questions', args=[self.title])
serializer.py:
class QuestionSerializer(serializers.ModelSerializer):
tags = TagSerializer(many=True )
answers = AnswerSerializer(many=True, read_only=True)
class Meta:
model = Question
fields = '__all__'
def create(self, validated_data):
tags_data = validated_data.pop('tags')
question = Question.objects.create(**validated_data)
for tag_data in tags_data:
tag = Tag.objects.create(**tag_data)
question.tags.add(tag)
question.save()
return question
urls.py:
from django.urls import path
from pages.api.views import *
from rest_framework import routers
from .routers import CustomRouter
from rest_framework.permissions import AllowAny
router = CustomRouter(trailing_slash=True)
router.register(r'questions', QuestionViewSet)
urlpatterns = []
urlpatterns + = router.urls
views.py:
class QuestionViewSet(mixins.ListModelMixin,
mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
GenericViewSet):
queryset = Question.objects.all()
serializer_class = QuestionSerializer
lookup_field = 'title'
permission_classes = [AllowAny]
routers.py:
from rest_framework.routers import Route, SimpleRouter, DefaultRouter
class CustomRouter(SimpleRouter):
"""
A router for read-only APIs, which doesn't use trailing slashes.
"""
routes = [
Route(
url=r'^{prefix}$',
mapping={'get': 'list'},
name='{basename}-list',
detail=False,
initkwargs={'suffix': 'List'}
),
Route(
url=r'^{prefix}/create$',
mapping={'post': 'create'},
name='{basename}-create',
detail=False,
initkwargs={'suffix': 'create'}
),
Route(
url=r'^{prefix}/{lookup}$',
mapping={'get': 'retrieve'},
name='{basename}-detail',
detail=True,
initkwargs={'suffix': 'Detail'}
),
Route(
url=r'^{prefix}/{lookup}/update$',
mapping={'patch': 'partial_update'},
name='{basename}-detail',
detail=True,
initkwargs={'suffix': 'Partial Update'}
),
Route(
url=r'^{prefix}/{lookup}/delete$',
mapping={'delete': 'destroy'},
name='{basename}-delete',
detail=True,
initkwargs={'suffix': 'Delete'}
),
]
我已经为我的http://127.0.0.1:8000/questions/ef/update准备了这个东西:
HTTP 405 Method Not Allowed
Allow: PATCH, OPTIONS
Content-Type: application/json
Vary: Accept
{"detail": "Method \"GET\" not allowed."}
它发回{“ detail”:“ not found”}。
我已经为我的http://127.0.0.1:8000/questions/ef/delete准备了这个东西:
HTTP 405 Method Not Allowed
Allow: DELETE, OPTIONS
Content-Type: application/json
Vary: Accept
{"detail": "Method \"GET\" not allowed."}
但是仍然可以删除项目。 顺便说一下,没有斜杠。
谢谢!