python - 在 Django 应用程序中显示特定用户详细信息而不是所有详细信息
问题描述
我正在创建我的第一个 Django 项目。我已将 30,000 个值作为输入,并希望根据主键显示特定值。
代码:
class employeesList(APIView):
def get(self,request):
employees1 = employees.objects.all()
with open('tracking_ids.csv') as f:
reader = csv.reader(f)
for row in reader:
_, created = employees.objects.get_or_create(
AWB=row[0],
Pickup_Pincode=row[1],
Drop_Pincode=row[2],
)
serializer = employeesSerializer(employees1 , many=True)
return Response(serializer.data)
def post(self,request):
# employees1 = employees.objects.get(id=request.employees.AWB)
employees1 = employees.objects.all()
serializer = employeesSerializer(employees1 , many=True)
return Response(serializer.data)
如果我在 URL 中输入http://127.0.0.1:8000/employees/ ,我会得到所有的值。我希望 URL 类似于http://127.0.0.1:8000/employees/P01001168074并显示 P01001168074 的值,其中 P01001168074 是主要 ID 。
我已阅读 1:显示特定用户 django 的模型值 2)在 python django rest 框架中编辑用户详细信息, 但它们不同
可以做到吗?如果可以,那怎么做?
解决方案
假设您使用的是 Django 2.0,您必须配置一个路径才能捕获您的参数,如文档中所示
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.serializers import ModelSerializer
class A(models.Model):
x = models.CharField(max_length=250)
class MySerializer(ModelSerializer):
class Meta:
model = A
fields = ('x',)
class MyListView(APIView):
def get(self, request, *args, **kwargs):
# simply get all the objects, serialize and return the response
elems = A.objects.all()
response_data = MySerializer(elems, many=True).data
return Response(data=response_data)
class MyDetailView(APIView):
def get(self, request, *args, **kwargs):
# we obtain the parameter from the URL
desired_item = kwargs.get("desired_item", None)
# we filter the objects by it and get our instance
element = A.objects.filter(x=desired_item).first()
# serialize the instance and return the response
response_data = MySerializer(element).data
return Response(data=response_data)
# all we have to now is define the paths for the list and the detail views.
urlpatterns = [
path('employees/', MyListView.as_view()),
path('employees/<str:desired_item>', MyDetailView.as_view())
]
推荐阅读
- linux - 如何在没有 STDIN 和 STDOUT 的情况下从 c 执行 bash 脚本
- excel - Acrobat Reader 4 - VBA 参考
- fortran - 解除分配导致程序停止而没有错误消息
- android - FAILURE:构建失败并出现异常:React Native
- javascript - 在 Angular 项目中集成 JavaScript 日历
- jquery - 如何使用 jQuery 将属性值复制到兄弟属性
- bash - 在 PhpStorm 中使用一个快捷方式上传多个文件
- regex - 如何使用基于自定义关键字和正则表达式的应用程序脚本在谷歌驱动器中搜索文件?
- php - 包含反引号的字符串的意外 strcmp 行为
- scala - 使用案例类的折叠和空实例从 List[IO(Abstraction[List[A]]]] 移动到 IO[Abstraction[List[A]]]