首页 > 解决方案 > 在 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 框架中编辑用户详细信息, 但它们不同

可以做到吗?如果可以,那怎么做?

标签: pythondjangoapidjango-rest-framework

解决方案


假设您使用的是 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())
]

推荐阅读