我正在编写一个小型应用程序。我将有两个端点:
/ generate-仅接受POST
/ exercise-它具有GET和PUT
我有以下模型:
class Exercise(models.Model):
created = models.DateTimeField(auto_now_add=True)
question = models.TextField(default='')
answered = models.BooleanField(default=False)
answer = models.TextField(default='',blank=True)
class Meta:
ordering = ['created']
def __str__(self):
return self.question
这是我想在每个端点上做的简单事情。
在/ generate POST上-在db中生成10个练习
在/ exercise GET上-返回未回答的问题
在/ exercise PUT上-更新“仅答案”并设置“已回答”字段。
这是我的序列化器
# snippets/serializers
from rest_framework import serializers
from .models import Exercise
class ExerciseSerializer(serializers.ModelSerializer):
class Meta:
model = Exercise
fields = ('id', 'question', 'answer')
class GenerateSerializer(serializers.ModelSerializer):
class Meta:
pass
model = None
model = Exercise
exercise = Exercise()
fields = ('id', 'question', 'answer')
最后查看:
from django.shortcuts import render
# Create your views here.
# snippets/views.py
from rest_framework import generics
from .models import Exercise
from .serializers import ExerciseSerializer, GenerateSerializer
class ExerciseList(generics.ListAPIView):
queryset = Exercise.objects.all()
serializer_class = ExerciseSerializer
class ExerciseDetail(generics.RetrieveUpdateAPIView):
queryset = Exercise.objects.all()
serializer_class = ExerciseSerializer
class GenerateExercise(generics.CreateAPIView):
# TODO: check if I need query set for create only method
# queryset = Exercise.objects.all()
serializer_class = GenerateSerializer
def perform_create(self, serializer): # new
for i in range(10):
serializer.save(question="{} + {} = ".format(i, i+1), answer=str(i+i+1))
当我运行/ generate时,我只有一个练习写入db。知道为什么吗? 其次,这是正确的方法吗?