【发布时间】:2015-03-25 05:33:24
【问题描述】:
我正在使用 Django 1.7.7 和 Django Rest Framework 3.1.1。
当我序列化这个模型时
class Question(models.Model):
QUESTION_TYPES = (
(10,'Blurb'),
(20,'Group Header'),
(21,'Group Footer'),
(30,'Sub-Group Header'),
(31,'Sub-Group Footer'),
(50,'Save Button'),
(100,'Standard Question'),
(105,'Text-Area Question'),
(110,'Multiple-Choice Question'),
(120,'Standard Sub-Question'),
(130,'Multiple-Choice Sub-Question')
)
type = models.IntegerField(default=100,choices=QUESTION_TYPES)
使用这个视图集/序列化器:
class QuestionSerializer(serializers.ModelSerializer):
type = serializers.ChoiceField(choices='QUESTION_TYPES')
class Meta:
model = Question
class QuestionViewSet(viewsets.ModelViewSet):
model = Question
serializer_class = QuestionSerializer
def get_queryset(self):
return Question.objects.all()
我得到一个 KeyError '10'(或者任何 QUESTION_TYPES 键是第一个从 Questions 表中序列化的键)。
错误似乎是由 to_representation 中的 rest_framework/fields.py 抛出的 return self.choice_strings_to_values[six.text_type(value)]
有什么明显的我做错了吗?使用带有 serializer.ChoiceField 的元组有问题吗?
约翰
【问题讨论】:
-
怎么样:
ChoiceField(choices=Question.QUESTION_TYPES)? -
这具有不抛出错误的理想效果,但它仍然显示键而不是诸如“blurb”之类的文本。我也试过
type = serializers.CharField(source='get_type_display'),虽然它正确显示了文本,而不是键,但它似乎是只读的。即使我尝试写密钥,我也无法终生写信。
标签: django django-rest-framework