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 
相關問題