我正在使用Django Rest Framework,并且尝试将$cabangs = Cabang::find()
->joinWith('idDpd')
->all();
foreach($cabangs as $index=>$model){
$model->idDpd->dpd;
}
模型中不存在的自定义字段添加到serializers.py文件中,到目前为止,代码如下,但是我遇到了错误。我知道HPIQuestionBank
和checkboxes
不是模型的属性,但我的目标是使它们checkboxValues
哪里出问题了? custom fields
是一个自定义字段,可以正常使用。
answer_type
序列化器
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'.
模型
class TemplateQuestionBankSerializer(serializers.ModelSerializer):
answer_type = serializers.CharField(write_only=True)
checkboxes = serializers.ListField(child=serializers.CharField(write_only=True))
checkboxValues = serializers.ListField(child=serializers.CharField(write_only=True))
class Meta:
model = HPIQuestionBank
fields = ['id','label','answer_type','checkboxes','checkboxValues']
答案 0 :(得分:1)
在序列化程序字段定义中,您拥有
checkboxes = serializers.ListField(child=serializers.CharField(write_only=True))
在这里,您已将子字段定义为只写,但还没有像这样定义ListField,因此序列化程序试图在序列化时获取其值。您需要定义以下字段:
checkboxes = serializers.ListField(child=serializers.CharField(write_only=True), write_only=True)
checkboxValues = serializers.ListField(child=serializers.CharField(write_only=True), write_only=True)
您可能不需要在子字段定义中添加只写,但是我不确定。