在django rest框架中如果我在序列化程序中使用DictField(),则在/ api / v1 / analytics / reports-configuration / 1 /给出我的AttributeError 'str'对象没有属性'items'错误。请看一下。
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)
错误:
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'