2017-08-30 51 views
0

嘗試django rest框架,可能有2個端點基於相同的模型返回不同的數據嗎? 我需要這樣的東西。創建2個基於同一模型的端點或方法 - django restframework

api/tarjetas應返回所有創建的對象,而api/tarjetasusuario應返回由特定用戶創建的對象。

感謝

class TarjetaViewSet(viewsets.ModelViewSet): 
 
    queryset = Tarjeta.objects.all() 
 
    serializer_class = TarjetaSerializer 
 
    permission_classes = (OwnerPermission,) 
 

 

 
class TarjetasusuarioViewSet(APIView): 
 
    queryset = Tarjeta.objects.all() 
 
    serializer_class = TarjetaSerializer 
 
    permission_classes = (OwnerPermission,) 
 

 
    def get_queryset(self): 
 
     return Tarjeta.objects.filter(usuario=self.request.user)

+0

爲什麼要寫兩個視圖?您可以使用GET參數編寫單個視圖集和過濾器......! – zaidfazil

+0

這段代碼對我來說似乎是正確的。你遇到的任何錯誤? –

+0

沒有錯誤,但我得到兩個相同的數據。也許問題出在路由器上?有任何想法嗎? 'code' 路由器= defaultrouter中() router.register(r'tarjetas',TarjetaViewSet) router.register(r'tarjetasusuario 'TarjetasusuarioViewSet) urlpatterns的= [ URL(R'^API- (r'^',include(router.urls)), ] + static(settings.STATIC_URL,document_root = settings.STATIC_ROOT,'auth /',include('rest_framework.urls',namespace ='rest_framework')), ) 'code' –

回答

0

嘗試用這種參考

class TarjetaViewSet(viewsets.ModelViewSet): 
    queryset = Tarjeta.objects.all() 
    serializer_class = TarjetaSerializer 
    permission_classes = (OwnerPermission,) 


class TarjetasusuarioViewSet(APIView): 
    user = User.objects.get(username=request.user) 
    queryset = Tarjeta.objects.filter(usuario=user) 
    serializer_class = TarjetaSerializer 
    permission_classes = (OwnerPermission,) 
0

我認爲你必須從ModelViewSet在TarjetasusuarioViewSet類擴展:

class TarjetaViewSet(viewsets.ModelViewSet): 
    queryset = Tarjeta.objects.all() 
    serializer_class = TarjetaSerializer 
    permission_classes = (OwnerPermission,) 


class TarjetasusuarioViewSet(viewsets.ModelViewSet): 
    queryset = Tarjeta.objects.all() 
    serializer_class = TarjetaSerializer 
    permission_classes = (OwnerPermission,) 

    def get_queryset(self): 
     return Tarjeta.objects.filter(usuario=self.request.user) 
相關問題