本文介绍了DRF序列化器字段DictField()AttributeError:'str'对象没有属性'items'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在django休息框架中如果我在序列化器中使用DictField(),它在/ api / v1 / analytics / reports-configuration / 1 /
'str'对象中给出了AttributeError AttributeError没有属性'items'error.please看看。



serializers.py

  import json 
from rest_framework import serializers

from models import ReportConfiguration


class ReportConfigurationSerializer(serializers.ModelSerializer):
report_type = serializers.ChoiceField(choices = ['query','activity','summary'])
read_only = serializers.BooleanField(required = True)
query_data = serializers.DictField(required = True)

class Meta:
model = ReportConfiguration

fields =('id','title','query_data','created_by','last_activity_by','deleted',
' deleted_by','added_at','last_activity_at','report_type','read_only')


def validate(self,data):
如果data ['report_type']不是summary,而data ['read_only']是True:
raise serializers.ValidationError (如果只读true,那么报告类型应该是摘要)
如果data ['report_type']是'summary',data ['read_only']不是True:
raise serializers.ValidationError(如果只读不正确,那么报告类型不应该是摘要)
返回数据

def create(self,validated_data):
validated_data ['created_by'] = self.context ['request']。user
validated_data ['last_activity_by'] = self.context ['request']。user
return ReportConfiguration.objects.create(** validated_data)

views.py

  class ReportConfigurationViewSet(viewsets.ModelViewSet):
serializer_class = ReportConfigurationSerializer
queryset = ReportConfiguration.obj ects.all()
permission_classes =(permissions.IsAuthenticated,)
filter_backends =(DjangoFilterBackend)
filter_class = ReportFilter

def list(self,request):
response = super(ReportConfigurationViewSet,self).list(request)
在response.data ['results']中的数据:
data ['query_data'] = json.loads(data [ 'query_data'])
return response

def retrieve(self,request,pk = None):
response = super(ReportConfigurationViewSet,self).retrieve(request,pk = pk)
response.data ['query_data'] = json.loads(response.data ['query_data'])
返回响应

models.py

  class ReportConfiguration(models.Model):
class ReportTypeChoice(Choice):
QueryReport ='query'
ActivityReport ='activity'
SummaryList ='summary'

title = models.CharField(max_length = 300,unique = True,blank = False,null = False)
query_data = JSONField(default = {})
created_by = models.ForeignKey(User,null = blank = True,related_name ='report_created_by')
last_activity_by = models.ForeignKey(User,null = True,blank = True,related_name ='last_active_in_report')
deleted = models.BooleanField(default = False)
deleted_by = models.ForeignKey(User,null = True,blank = True,related_name ='report_deleted_by')
added_at = models.DateTimeField(auto_now_add = True)
last_activity_at = models.DateTimeField default = timezone.now)
report_type = models.CharField(max_length = 15,choices = ReportTypeChoice)
read_only = models.BooleanField(default = False)
/ pre>

错误:

 启动开发服务器在http: /127.0.0.1:8000/ 
使用CONTROL-C退出服务器。
错误内部服务器错误:/ api / v1 / analytics / reports-configuration / 1 /
追溯(最近的最后一次呼叫):
文件/Users/ranvijay.s/.virtualenvs/ my_project / lib / python2.7 / site-packages / django / core / handlers / base.py,第149行,get_response
response = self.process_exception_by_middleware(e,request)
文件/ Users /ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/django/core/handlers/base.py,第147行,在get_response
response = wrapped_callback(request,* callback_args,* * callback_kwargs)
文件/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/django/views/decorators/csrf.py,第58行,wrapped_view
return view_func(* args,** kwargs)
文件/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/rest_framework/viewsets.py,第83行,查看
return self.dispatch(request,* args,** kwargs)
文件/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/ rest_framework / views.py,第477行,在调度中
response = self.handle_exception(exc)
文件/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site- package / rest_framework / views.py,第437行,handle_exception
self.raise_uncaught_exception(exc)
文件/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site- package / rest_framework / views.py,第474行,在调度中
response = handler(request,* args,** kwargs)
文件/Users/ranvijay.s/wk/project/django/ dhanalytics / views.py,第47行,检索
response = super(ReportConfigurationViewSet,self).retrieve(request,pk = pk)
文件/Users/ranvijay.s/.virtualenvs/my_project /lib/python2.7/site-packages/rest_framework/mixins.py,第58行,检索
返回响应(serializer.data)
文件/Users/ranvijay.s/.virtualenvs/ my_project / lib / python2.7 / site-packages / rest_framework / serializers.py,第527行,数据
ret = super(Serializer,self).data
Fi le/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/rest_framework/serializers.py,第262行,数据
self._data = self.to_representation(self。实例)
文件/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/rest_framework/serializers.py,第496行,to_representation
ret [field。 field_name] = field.to_representation(attribute)
文件/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/rest_framework/fields.py,第1601行,to_representation
为key,val为value.items()
AttributeError:'str'对象没有属性'items'
解决方案

你需要传递DictField需要通过

  d验证的子字段ocument = DictField(child = CharField())


In django rest framework If i use DictField() in serializer its given me AttributeError at /api/v1/analytics/reports-configuration/1/‘str’ object has no attribute ‘items’ error.please take a look.

serializers.py

import json
from rest_framework import serializers

from models import ReportConfiguration


class ReportConfigurationSerializer(serializers.ModelSerializer):
    report_type = serializers.ChoiceField(choices=['query', 'activity', 'summary'])
    read_only = serializers.BooleanField(required=True)
    query_data = serializers.DictField(required=True)

    class Meta:
        model = ReportConfiguration

        fields = ('id', 'title', 'query_data', 'created_by', 'last_activity_by', 'deleted',
                  'deleted_by', 'added_at', 'last_activity_at', 'report_type', 'read_only')


    def validate(self, data):
        if data['report_type'] is not 'summary' and data['read_only'] is True:
            raise serializers.ValidationError("If read only true then report type should be summary")
        if data['report_type'] is 'summary' and data['read_only'] is not True:
            raise serializers.ValidationError("If read only not true then report type should not be summary")
        return data

    def create(self, validated_data):
        validated_data['created_by'] = self.context['request'].user
        validated_data['last_activity_by'] = self.context['request'].user
        return ReportConfiguration.objects.create(**validated_data)

views.py

class ReportConfigurationViewSet(viewsets.ModelViewSet):
    serializer_class = ReportConfigurationSerializer
    queryset = ReportConfiguration.objects.all()
    permission_classes = (permissions.IsAuthenticated,)
    filter_backends = (DjangoFilterBackend,)
    filter_class = ReportFilter

    def list(self, request):
        response = super(ReportConfigurationViewSet, self).list(request)
        for data in response.data['results']:
            data['query_data'] = json.loads(data['query_data'])
        return response

    def retrieve(self, request, pk=None):
        response = super(ReportConfigurationViewSet, self).retrieve(request, pk=pk)
        response.data['query_data'] = json.loads(response.data['query_data'])
        return response 

models.py

class ReportConfiguration(models.Model):
    class ReportTypeChoice(Choice):
        QueryReport = 'query'
        ActivityReport = 'activity'
        SummaryList = 'summary'

    title = models.CharField(max_length=300, unique=True, blank=False, null=False)
    query_data = JSONField(default={})
    created_by = models.ForeignKey(User, null=True, blank=True, related_name='report_created_by')
    last_activity_by = models.ForeignKey(User, null=True, blank=True,related_name='last_active_in_report')
    deleted = models.BooleanField(default=False)
    deleted_by = models.ForeignKey(User, null=True, blank=True, related_name='report_deleted_by')
    added_at = models.DateTimeField(auto_now_add=True)
    last_activity_at = models.DateTimeField(default=timezone.now)
    report_type = models.CharField(max_length=15, choices=ReportTypeChoice)
    read_only = models.BooleanField(default=False)

Error:

Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
ERROR Internal Server Error: /api/v1/analytics/reports-configuration/1/
Traceback (most recent call last):
  File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/rest_framework/viewsets.py", line 83, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/rest_framework/views.py", line 477, in dispatch
    response = self.handle_exception(exc)
  File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/rest_framework/views.py", line 437, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/rest_framework/views.py", line 474, in dispatch
    response = handler(request, *args, **kwargs)
  File "/Users/ranvijay.s/wk/project/django/dhanalytics/views.py", line 47, in retrieve
    response = super(ReportConfigurationViewSet, self).retrieve(request, pk=pk)
  File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/rest_framework/mixins.py", line 58, in retrieve
    return Response(serializer.data)
  File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/rest_framework/serializers.py", line 527, in data
    ret = super(Serializer, self).data
  File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/rest_framework/serializers.py", line 262, in data
    self._data = self.to_representation(self.instance)
  File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/rest_framework/serializers.py", line 496, in to_representation
    ret[field.field_name] = field.to_representation(attribute)
  File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/rest_framework/fields.py", line 1601, in to_representation
    for key, val in value.items()
AttributeError: 'str' object has no attribute 'items'
解决方案

you need to pass the child field which the DictField needs to get validated with

document = DictField(child=CharField())

这篇关于DRF序列化器字段DictField()AttributeError:'str'对象没有属性'items'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 04:17