Django - 如何从另一个API映射对象并发送GET响应

时间:2017-06-10 14:25:51

标签: python django python-3.x django-models django-rest-framework

我想从另一个API映射对象并发送GET响应。我只会更改收到的对象的from tensorflow.contrib.learn.python.learn.utils import input_fn_utils serving_input_fn = input_fn_utils.build_parsing_serving_input_fn(feature_spec) 。我们假设我以这种格式从另一个API获取数据:

id

在我的数据库中,我有表{ "id": "31242", "name": "sth1", "price": "44", "data": "2017-06-07", } ,其值为:

object1

字段{ "id": "123", "name": "sth1", }, { "id": "124", "name": "sth2", }, { "id": "125", "name": "sth3", } 在来自API的数据和来自数据库的数据中都是唯一的。我收到一个名为name的对象。所以现在我想在我的数据库中找到它并获取他的sth1,用API替换id并发送GET响应。在这种情况下,我的回答会这样:

id

目前这是我的网址 - { "id": "123", "name": "sth1", "price": "44", "data": "2017-06-07", } 但是我希望有这样的网址 - url(r'^data/(?P<name>\w+)$', views.DataList), 我的localhost:8000/data?name=sth

view.py

@api_view(['GET']) def DataList(request, name=None): if request.method == 'GET': quote = getDataFromAPI().get(name) return Response(quote)

serializers.py

class Object1Serializer(serializers.ModelSerializer): class Meta: model = Object1 depth = 1 fields = '__all__'

models.py

我是这样做的:

class Object1(models.Model):

    name = models.CharField(max_length=200)

但我收到错误: @api_view(['GET']) def DataList(request): t = request.GET.get("t","") quote = getDataFromAPI().get(t) id = Object1.objects.get(t=t) quote["id"] = id return Response(quote)

2 个答案:

答案 0 :(得分:0)

如果您想更改来自的网址 url(r'^data/(?P<name>\w+)$', views.DataList)localhost:8000/data?name=sth您需要更改

@api_view(['GET'])
def DataList(request, name=None):

@api_view(['GET'])
def DataList(request):
    name = request.GET.get("name","")

然后通过查询

从数据库中获取对象的id
id = Object1.objects.get(name=name)

然后更新id以响应发送

quote["id"] = id

答案 1 :(得分:0)

我想,你的观点应该看起来像这样,

@api_view(['GET']) 
def DataList(request): 
    t = request.GET.get("t","") 
    quote = getDataFromAPI().get(t) 
    id = Object1.objects.get(t=t).id #put the id of the object in the variable.
                   #not the object itself.
    quote["id"] = id 
    return Response(quote)