django

时间:2018-02-15 05:15:10

标签: django python-3.x

我正在尝试在django中使用REST API来检索json格式的一些数据 当我点击这个网址时:

  

http://192.168.2.87:8000/locker/123/

它给我这样的输出(来自数据库)

  

{“id”:1,“locker_id”:123,“locker_user_name”:“taimur”}

但是如果我想通过传递像这样的参数来获得输出

  

http://192.168.2.87:8000/locker/?locker_id=123&locker_user_name=taimur&id=1

views.py

from postman, How can i do this??
from django.shortcuts import render, HttpResponse, get_object_or_404
from django.http import JsonResponse
from .models import Locker
from .serializers import LockerSerializer
from rest_framework.response import Response
from rest_framework import status
from rest_framework.views import APIView


def locker_data_response(request, locker_id):
    if request.method == 'GET':
        locker_information = get_object_or_404(Locker, locker_id = locker_id)
        print(locker_information)
        locker_information_serialize = LockerSerializer(locker_information)
        print(locker_information_serialize)
        return JsonResponse(locker_information_serialize.data)

urls.py

from django.urls import path, re_path
from . import views

urlpatterns = [
    re_path('(?P<locker_id>[0-9]+)/$', views.locker_data_response, name='locker_data_response'),
]

2 个答案:

答案 0 :(得分:0)

您可以从request对象获取它们:

def locker_data_response(request):
if request.method == 'GET':
    locker_id = request.data.get('locker_id')  # this will return None if not found
    locker_user_name = request.data.get('locker_user_name')
    locker_information = get_object_or_404(Locker, locker_id=locker_id)
    print(locker_information)
    locker_information_serialize = LockerSerializer(locker_information)
    print(locker_information_serialize)
    return JsonResponse(locker_information_serialize.data)

url将更改为:

locker/$

[编辑:抱歉,如果您使用drf,则应使用data而不是GET]

[编辑2:如果你想这样使用它,你还需要更改url的{​​{1}}和签名

[编辑3:在视图中的正确位置添加了代码]

答案 1 :(得分:0)

如果您的网址类似domain/search/?q=haha,那么您可以使用request.GET.get('q', '')

q是您想要的参数,''是默认值,如果找不到q

如果您只是配置URLconf,那么regex中的捕获将作为参数(或命名参数)传递给函数。

如:

(r'^user/(?P<username>\w{0,50})/$', views.profile_page,),

然后在你的views.py中你会有

def profile_page(request, username):
    # Rest of the method