gpt4 book ai didi

python - Django 2.0,一级类 View ,AttributeError : 'str' object has no attribute 'values'

转载 作者:行者123 更新时间:2023-12-01 09:31:04 25 4
gpt4 key购买 nike

我在 Django 2.0 中创建了一个通用 View 和序列化器,这样我就不必重复创建 CRUD View 或序列化器。

我的API应用程序的views.py文件

from rest_framework import generics, mixins
from rest_framework.serializers import ModelSerializer


class StandardListMixinCreateApiView(mixins.CreateModelMixin, generics.ListAPIView):
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)


class StandardRudApiView(generics.RetrieveUpdateDestroyAPIView):
lookup_field = 'pk'

此函数设置每个启用模型的serializer.Meta.model。`cls 参数是 StandardApiView 之一。

def get_adapted_class(cls, model_class, serializer_fields='__all__'):

class AdaptedSerializer(ModelSerializer):
class Meta:
model = model_class

fields = serializer_fields

class AdaptedView(cls):
model = model_class.__name__
queryset = model_class.objects.all()
serializer_class = AdaptedSerializer

return AdaptedView

我的 urls.py

from django.urls import re_path
from .views import *
from django.contrib.auth.models import Group, Permission
from .models import *

app_name = "api"

为其生成 CRUD View 的模型。

ENABLEDMODELS = [
Address,
Group,
Permission,
Customer,
Employee,
Commission,
BugReport,
FeatureRequest,
]

APILISTVIEWS = [get_adapted_class(
StandardListMixinCreateApiView,
model) for model in ENABLEDMODELS]

APIRUDVIEWS = [get_adapted_class(
StandardRudApiView,
model) for model in ENABLEDMODELS]

将每个创建的 ListView 的 url 路由添加到 urlpatterns

# List, create views
urlpatterns = [re_path(
f'^(?i){class_view.model}/',
class_view.as_view(),
name=f'{class_view.model}-list') for class_view in APILISTVIEWS]

# Retrive, update, delete views
urlpatterns += [re_path(
f'^(?i){class_view.model}/' + r'(?P<pk>\d+)',
class_view.as_view(),
name=f'{class_view.model}-rud') for class_view in APIRUDVIEWS]

错误消息

Environment:


Request Method: GET
Request URL: http://localhost:8000/api/address/

Django Version: 2.0.4
Python Version: 3.6.5
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'api']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "C:\Users\Steffen22\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py" in inner
35. response = get_response(request)

File "C:\Users\Steffen22\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response
158. response = self.process_exception_by_middleware(e, request)

File "C:\Users\Steffen22\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response
156. response = response.render()

File "C:\Users\Steffen22\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\response.py" in render
106. self.content = self.rendered_content

File "C:\Users\Steffen22\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\response.py" in rendered_content
72. ret = renderer.render(self.data, accepted_media_type, context)

File "C:\Users\Steffen22\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\renderers.py" in render
724. context = self.get_context(data, accepted_media_type, renderer_context)

File "C:\Users\Steffen22\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\renderers.py" in get_context
656. raw_data_post_form = self.get_raw_data_form(data, view, 'POST', request)

File "C:\Users\Steffen22\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\renderers.py" in get_raw_data_form
572. data = serializer.data.copy()

File "C:\Users\Steffen22\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\serializers.py" in data
560. ret = super(Serializer, self).data

File "C:\Users\Steffen22\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\serializers.py" in data
266. self._data = self.get_initial()

File "C:\Users\Steffen22\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\serializers.py" in get_initial
413. for field in self.fields.values()

Exception Type: AttributeError at /api/address/
Exception Value: 'str' object has no attribute 'values'

最佳答案

我找到了一个解决方案来重用我的标准 REST View 、序列化器并根据它们生成 url。

'api/views.py'

from rest_framework import generics, mixins
from rest_framework.serializers import ModelSerializer


class StandardListMixinCreateApiView(mixins.CreateModelMixin, generics.ListAPIView):
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)


class StandardRudApiView(generics.RetrieveUpdateDestroyAPIView):
lookup_field = 'pk'


def get_adapted_class(cls, model_class, serializer_fields='__all__'):
class AdaptedView(cls):
model = model_class.__name__

我必须重写 get_serializer_class 函数,而不是设置 serializer_class 属性。

        def get_serializer_class(self):
class BaseSerializer(ModelSerializer):
class Meta:
model = model_class
fields = serializer_fields
return BaseSerializer

def get_queryset(self):
return model_class.objects.all()

return AdaptedView

那些标准的ApiViews很容易使用,你可以创建一个新的django模型并将模型类添加到ENABLEDMODELS列表中

'api/urls.py'

from django.urls import re_path
from .views import *
from django.contrib.auth.models import Group, Permission
from .models import *

app_name = "api"

ENABLEDMODELS = [
Address,
Group,
Permission,
Customer,
Employee,
Commission,
BugReport,
FeatureRequest,
]

APILISTVIEWS = [get_adapted_class(
StandardListMixinCreateApiView,
model) for model in ENABLEDMODELS]

APIRUDVIEWS = [get_adapted_class(
StandardRudApiView,
model) for model in ENABLEDMODELS]

在 2.0 以下的 Django 版本中,path/re_path 方法称为 url,如果您更改它也应该在旧版本中工作。

re_path 方法用于 Django 2.0 中的正则表达式路由

# List, create views
urlpatterns = [re_path(
f'^(?i){class_view.model}/',
class_view.as_view(),
name=f'{class_view.model}-list') for class_view in APILISTVIEWS]

# Retrive, update, delete views
urlpatterns += [re_path(
f'^(?i){class_view.model}/' + r'(?P<pk>\d+)',
class_view.as_view(),
name=f'{class_view.model}-rud') for class_view in APIRUDVIEWS]

关于python - Django 2.0,一级类 View ,AttributeError : 'str' object has no attribute 'values' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49961120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com