在Django应用程序中显示特定的用户详细信息,而不是所有详细信息

时间:2018-12-16 13:15:18

标签: python django api django-rest-framework

我正在创建我的第一个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:showing the model values of specific user django 2)editing user details in python django rest framework 但它们不同

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

2 个答案:

答案 0 :(得分:2)

假设您使用的是Django 2.0,则必须配置路径才能捕获参数as seen in the documentation

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())
]

答案 1 :(得分:1)

一个不错的选择是使用viewset,它已经包括一个列表和详细信息终结点,并且只需很少的代码即可进行默认的简单设置

views.py

from rest_framework import viewsets


class EmployeeViewSet(viewsets.ModelViewSet):
    serializer_class = EmployeeSerializer
    queryset = Employee.objects.all()

urls.py

from rest_framework.routers import SimpleRouter
from views import EmployeeViewSet


router = SimpleRouter()
router.register(r'employees', EmployeeViewSet, base_name='employees')

urlpatterns = router.get_urls()

您可以在DRF docs

中了解有关视图集的更多信息