I am new to DRF.
I read the API docs, maybe it is obvious but I couldn't find a handy way to do it.
I have an Answer
object which has one-to-one relationship with a Question
.
On the frontend I used to use POST method to create an answer sent to api/answers
, and PUT method to update sent to e.g. api/answers/24
But I want to handle it on the server side. I will only send a POST method to api/answers
and DRF will check based on answer_id
or question_id
(since it is one to one) if the object exists.
If it does, it will update the existing one, and if it doesn't, it will create a new answer.
I couldn't figure out where I should implement it. Should I override create()
in serializer or in ViewSet or something else?
Here are my model, serializer, and view:
class Answer(models.Model):
question = models.OneToOneField(
Question, on_delete=models.CASCADE, related_name="answer"
)
answer = models.CharField(
max_length=1, choices=ANSWER_CHOICES, null=True, blank=True
)
class AnswerSerializer(serializers.ModelSerializer):
question = serializers.PrimaryKeyRelatedField(
many=False, queryset=Question.objects.all()
)
class Meta:
model = Answer
fields = ("id", "answer", "question")
class AnswerViewSet(ModelViewSet):
queryset = Answer.objects.all()
serializer_class = AnswerSerializer
filter_fields = ("question", "answer")
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…