Skip to main content
 首页 » 编程设计

python之Django 'Request' 对象没有属性 'user_id'

2025年05月04日22dyllove98

在我的 urls.py 中我有:

url(r'^dashboard/users/(?P<user_id>[0-9]+)/products/$', views.UserProductsList.as_view()) 

在views.py

中
class UserProductsList(generics.ListCreateAPIView): 
     def get_queryset(self): 
         if self.request.user_id: 
             return UserProducts.objects.filter(user_id=self.request.user_id).order_by('id') 
         else: 
             return UserProducts.objects.all().order_by('id') 

我希望能够这样访问我的 api:

http://localhost:8000/dashboard/users/10/products

应该列出该用户的所有产品,并且

http://localhost:8000/dashboard/users/10/products/1

应该返回 user_id 10 的 product_id 1

我该如何实现这个流程。

Note: I'm using Django rest framework in this setup

请您参考如下方法:

你可以做到

class UserProductsList(generics.ListCreateAPIView): 
     def get_queryset(self): 
         if self.kwargs['user_id']: 
             return UserProducts.objects.filter(user_id=self.kwargs['user_id']).order_by('id') 
         else: 
             return UserProducts.objects.all().order_by('id') 

引用doc