1

在我urls.py我:Django的 '请求' 对象有没有属性 'USER_ID'

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我如何能实现此流程。

注:我使用Django的REST框架在此设置

+1

怎么样'self.request.user.id'? – itzMEonTV

+0

我在路线中提到过'(?P )'那么为什么'self.request.user.id'中会有任何东西? –

回答

4

你可以做

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

0

请更新您的代码,这样的..

class UserProductsList(generics.ListCreateAPIView): 
def get_queryset(self): 
    if self.request.user.id: 
     return 

或者

class UserProductsList(generics.ListCreateAPIView): 
def get_queryset(self): 
    if self.kwargs['user_id']: 
     return 
相关问题