Django:如何在基于类的视图中获取ID?

时间:2019-03-12 09:02:44

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

views.py

from paitent.mixini import HttpResponseMixin,SerializeMixin
from paitent.models import Paitent_Details

class PaitentCRUDCBV(View, HttpResponseMixin, SerializeMixin):

   def get(self, id, *args, **kwargs):
      paitent = Paitent_Details.objects.get(id=id)
      json_data = self.render_to_serialize([paitent,])
      return self.render_to_http_response(json_data)

urls.py

urlpatterns = [
   url(r'^api/json',views.PaitentCRUDCBV.as_view()),
]

我的要求基于id,我必须从前端获取特定的行表单数据库,我在url中传递id,例如:(url:“ http://127.0.0.1:8000/api/json/?id=2”)。但是我没有在班上找到id,不知道我在哪里做错了。请帮助我。

2 个答案:

答案 0 :(得分:0)

您可以在视图中使用query_params:

def get(self, request): id = self.request.query_params.get('id')
....

You can get more information from documentation

答案 1 :(得分:0)

1)I have edited your following code, you have to pass *request* in your function,
2)Inside the function calling request.query_params.get, you will get parameters value from the url  



from paitent.mixini import HttpResponseMixin,SerializeMixin
from paitent.models import Paitent_Details

class PaitentCRUDCBV(View, HttpResponseMixin, SerializeMixin):

   def get(self, request, *args, **kwargs):
      id=self.request.query_params.get('id')
      paitent = Paitent_Details.objects.get(id=id)
      json_data = self.render_to_serialize([paitent,])
      return self.render_to_http_response(json_data)