我有以下代码段
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
class QuestionSerializer(serializers.ModelSerializer):
class Meta:
fields = '__all__'
model = Question
class ChoiceSerializer(serializers.ModelSerializer):
class Meta:
fields = '__all__'
model = Choice
depth = 1
class ChoiceAPI(ModelViewSet):
queryset = Choice.objects.all()
serializer_class = ChoiceSerializer
目前我的输出为,
[
{
"id": 1,
"choice_text": "choice-1",
"votes": 1,
"question": {
"id": 1,
"question_text": "Maximizing Assassin damage",
"pub_date": "2018-07-13T13:29:36Z"
}
}
]
现在,我希望使用有效负载创建新的Choice
实例,
{
"choice_text": "choice-1",
"votes": 1,
"question": 1
}
但是,当我尝试上述有效负载时,
是我的例外IntegrityError at /sample/test/
NOT NULL constraint failed: sample_choice.question_id.
搜索完Google之后,我找到了一种方法来解决此问题,方法是重写get_serializer_class()
的{{1}}方法。
我的问题是,有没有办法做到这一点而不会覆盖ModelViewSet
的get_serializer_class()
方法?
答案 0 :(得分:1)
您可以覆盖__init__()
类的ModerSerializer
,
class ChoiceSerializer(serializers.ModelSerializer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if 'view' in self.context and self.context['view'].action == 'create':
self.fields.update({"question": serializers.PrimaryKeyRelatedField(queryset=Question.objects.all())})
class Meta:
fields = '__all__'
model = Choice
depth = 1
您还可以使用viewset actions
限制设置,有关更多详细信息,请阅读Viewset actions
注意:我没有测试该解决方案,但可能效果很好
参考:Django Rest Framework: Dynamically return subset of fields