使用Django Rest Framework时如何创建自定义列表字段

时间:2019-04-01 09:24:23

标签: django python-3.x serialization django-rest-framework django-serializer

我有以下模型,我想添加一个名为choices的自定义字段,它将作为选择的列表。

class HPIQuestionBank(models.Model):
    label = models.CharField(
        max_length=200,
        db_index=True,
        blank=True,
        null=True)
    template = models.ForeignKey(
        HPIFilter, blank=True, null=True, on_delete=models.CASCADE, default='')

我在序列化程序中实现了以下内容。

class CheckBoxesListField(serializers.ListField):
    child = serializers.CharField(allow_null = True, allow_blank=True)

class TemplateQuestionBankSerializer(serializers.ModelSerializer):
    answer_type = serializers.CharField(allow_null = True, allow_blank=True)
    checkboxes = CheckBoxesListField()

    hpianswers_set =TemplateAnswerSerializer(many=True)
    class Meta:
        model = HPIQuestionBank
        fields = ['id','label','hpianswers_set','answer_type','checkboxes']

我在GET方法上使用了序列化器。当我尝试发出请求时,出现以下错误:

AttributeError at /api/clinic2/history/template/6/
Got AttributeError when attempting to get a value for field `checkboxes` on serializer `TemplateQuestionBankSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `HPIQuestionBank` instance.
Original exception text was: 'HPIQuestionBank' object has no attribute 'checkboxes'. 

1 个答案:

答案 0 :(得分:0)

如果您只需要读取数据,则可以尝试:

class Meta:
    model = HPIQuestionBank
    fields = ['id','label','hpianswers_set','answer_type',]
    read_only_fields = ['checkboxes',]

或者您可以与SerializerMethodField一起使用

class TemplateQuestionBankSerializer(serializers.ModelSerializer):
    answer_type = serializers.CharField(allow_null = True, allow_blank=True)
    checkboxes = SerializerMethodField()

    def get_checkboxes(self, instance):
        return CheckBoxesListField(instance).data