【问题标题】:How can I successful POST a Choice that is linked to a Question in a Poll's API in Django?如何在 Django 中成功发布与投票 API 中的问题相关联的选项?
【发布时间】:2021-10-25 12:00:11
【问题描述】:

我正在创建一个调查/投票 api,我可以成功发布问题,但我收到以下错误 Choice() got an unexpected keyword argument 'question' 当我尝试创建与问题相关联的选择时,我想不通。

这些是模型

from django.db import models
import datetime
from django.utils import timezone
# Модели для опоросов
class Question(models.Model):
    poll_question = models.CharField(max_length=255, blank=False)
    title = models.CharField(max_length=255, blank=True)
    start_date = models.DateTimeField('date published', blank=False)
    
    def __str__(self):
        return self.poll_question
    
    def published_not_longage(self):
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.start_date <= now
    
 
       
#Модель для Выбора
class Choice(models.Model):
    poll_question = models.ForeignKey(Question, on_delete=models.CASCADE)
    poll_question_choice = models.CharField(max_length=255)
    votes = models.IntegerField(default=0)




The choices serializer
class ChoiceSerializer(serializers.Serializer):
    poll_question_choice = serializers.CharField(max_length=255)
    
    def create(self, validated_data):
        return Choice.objects.create(**validated_data)


#The choices view

- The error is arising when I pass in the question instance in the serializer.save() method.

@api_view(['POST'])
def choice_details(request, pk):
    question = Question.objects.get(pk=pk)
    # question = get_object_or_404(Question, pk=pk)
    serializer = ChoiceSerializer(data=request.data)
    if serializer.is_valid():
        poll_question_choice = serializer.save(question=question)
        return Response(ChoiceSerializer(poll_question_choice).data, status=status.HTTP_201_CREATED)
    return  Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

【问题讨论】:

    标签: django django-rest-framework rest django-serializer django-registration


    【解决方案1】:

    根据模型Choice,该字段被命名为poll_question,因此需要在save 中使用(而不是question):

    poll_question_choice = serializer.save(poll_question=question)
    

    【讨论】:

    • 哇,感谢解决它的人。
    猜你喜欢
    • 1970-01-01
    • 2019-05-01
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多