我的项目结构如下,
..
├── project
│ ├── app1
│ └── app2
│ ├── app2_views
│ ├── main_view.py
│ ├── view1.py
│ ├── view2.py
我想在我的view1.py
中调用main_view.py
中定义的类
我尝试了以下代码,
main.py
from rest_framework import viewsets
from app2.app2_views.view1.py import class1
class mainclass(viewsets.ModelViewSet):
class1.view1_data()
view1.py
from app2.models.py import table1
from rest_framework import viewsets
from app2.serializers.py import seri1
from django.db.models import Sum
class class1(viewsets.ModelViewSet):
def view1_data():
queryset = table1.objects.values('column')
serializer_class = seri1
seri1.py
from rest_framework import serializers
from app2.models import table1
class seri1(serializers.HyperlinkedModelSerializer):
class Meta:
model = table1
fields = ['column']
但是我在main.py说
时遇到错误should either include a `serializer_class` attribute, or override the `get_serializer_class()` method
因为我已经在view1.py
中加入了序列化程序类,所以我不想在main_view.py
中再做一次。
我是python的新手,我在这里做错了什么?
我也想保持view1.py>class1
和main.py>mainclass
都可以通过url(其余框架管理门户)访问吗?
当前我的urls.py是,
from django.urls import include, path
from rest_framework import routers
from . import views
from .app2 import view1, main_view
router = routers.DefaultRouter(trailing_slash=False)
router.register(r'^view1', main_view.mainclass, basename='mis_trx_data')
router.register(r'^main_view', view1.class1, basename='mis_trx_data')
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
谢谢您的建议
答案 0 :(得分:0)
您需要在serializer_class
中指定一个名为ModelViewSet
的类级别变量
class class1(viewsets.ModelViewSet):
serializer_class = MySerializer
def view1_data():
queryset = table1.objects.values('column')
serializer = self.serializer_class(request.data)
Ajax请求将表单数据发送到API
$.ajax({
url: api-end-point,
data: JSON.stringify($("#form").serialize()),
success: function (E){
console.log("sucess");
},
error: function(e){
console.log("error");
}
});