看来在django没有办法这样做。
这不是最好的解决方案,
有时,根据关系需要不同的序列化程序类
我刚刚创建了一个有效的脚本:
您只需要从项目目录运行它,并将应用程序名称作为参数
`import os
import sys
ROUTER_TEMPLATE = "router.register(r'{}', views.{}ViewSet)"
SERIALIZER_TEMPLATE = """
class {}Serializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = {}
fields = '__all__'
"""
VIEW_TEMPLATE= """
class {}ViewSet(viewsets.ModelViewSet):
queryset = {}.objects.all()
serializer_class = {}Serializer
"""
def gen_api(app_name):
models= open(app_name+'/models.py', 'r')
aLines = models.readlines()
for sLine in aLines:
aLine = sLine.split()
for sWord in aLine:
if sWord == "class" and aLine[aLine.index(sWord)+1] != "Meta:":
model_name= aLine[aLine.index(sWord)+1].split("(")[0]
gen(app_name,model_name )
def gen(app_name, name):
config = open(app_name+'/urls.py', 'a') #append
config.write("\n"+ ROUTER_TEMPLATE.format(name, name))
config.close()
config = open(app_name+'/serializers.py', 'a') #append
config.write("\n"+ SERIALIZER_TEMPLATE.format(name, name))
config.close()
config = open(app_name+'/views.py', 'a') #append
config.write("\n"+ VIEW_TEMPLATE.format(name, name, name))
config.close()
if __name__ == "__main__":
gen_api(sys.argv[1])
`