在工作中需要编写API接口。随着需求的改变,API接受的参数也不一样,于是有了一个想法,就是“有没有办法把URL里面的参数尽量做成跟后端Model里的Field一致?”。这样,就可以让维护变得更简单一点。
Django是一个比较完善的框架,以至于许多过程都被封装了。但是,我相信封装过程中会有一些不太常用的“中间产品”,或许能派上用场。经过搜索,发现这个思路确实可以。
代码如下(一个views里面的view class)
from django.db.models.fields.related import ForeignKey
from django.db.models import CharField, DecimalField, IntegerField
from django.apps import apps
class DealersView(APIView):
data_models = apps.get_app_config('dealers').get_models()
try:
for data_model in data_models:
if data_model.__name__ == request.GET['class']:
print("Got a Correct Class name.")
data_model_to_return = data_model
break
fields = data_model_to_return._meta.fields
field_names = [field.name for field in fields]
key_words = {}
for item in request.GET:
if item in field_names and request.GET[item] != '' \
and item != "class":
if not isinstance(fields[field_names.index(item)], ForeignKey):
key_words[item] = request.GET[item]
print(item + str(request.GET[item]))
else:
key_words[item] = data_model_to_return._meta.get_field(item).related_model.objects.get(id=int(request.GET[item]))
objList = data_model_to_return.objects.filter(**key_words)
if objList == []:
objList = data_model_to_return.objects.all()
try:
ser = DealerSerializer(objList, many=True)
except:
ser = DealerSerializer(objList, many=True)
return Response(ser.data)
except:
pass
return Response([])
def post(self, request, *args, **kwargs):
pass
以上是大致的代码,当然还需要完善。鉴于现阶段对permission等议题并无要求,先维持这样。
网友评论