字段字段名称`test`对于模型`Ability`无效

时间:2015-08-21 14:39:18

标签: python django django-rest-framework

我有一个没有字段'test'的模型。我在运行时分配这个字段:

ability = Ability.objects.first()
ability.test = 'TEST!!'

我也有serilizer:

class AbilitySerializer(serializers.ModelSerializer):
    class Meta:
        model = Ability
        fields = ('name', 'test',)

当我使用它时:

return Response(AbilitySerializer(ability).data)

我收到错误:

Field Field name `test` is not valid for model `Ability`.

编辑:当我将对象数组传递给序列化程序时,我仍然面临这个问题(许多= True)。当我传递单个实例时,它没关系。

为什么以及如何解决它?

1 个答案:

答案 0 :(得分:2)

正如Ajay Gupta指出的那样,必须明确声明非模型字段/方法/属性:

<ul class="nav nav-tabs">

    <li class="active"><a href="#tab1primary" data-toggle="tab">Dashboard</a></li>
    <?php  
  if (($this->session->userdata('user_type'))==1)
  { ?>                                                        

          <li><a href="#tab2primary" data-toggle="tab">Business</a></li>

    <?  }  
   ?>  

    <li><a href="#tab3primary" data-toggle="tab">Events</a></li>
    <li><a href="#tab4primary" data-toggle="tab">Event Reviews</a></li>
    <li><a href="#tab5primary" data-toggle="tab">Business Reviews</a></li>
</ul>

此外,如果您不总是提供class AbilitySerializer(serializers.ModelSerializer): # read_only since test is not a model field test = serializers.CharField(read_only=True) class Meta: model = Ability fields = ('name', 'test',) ,请考虑:

test