简体   繁体   中英

retrieve data for current user only in DRF

I was wondering how can I limit the queryset to the data associated with the current user. Here is my view:

class TradingGroupList(generics.ListAPIView):
        queryset = Tradegroup.objects.all()
        serializer_class = TradeGroupSerializer
        name = 'tradegroup-list'

I would write somethinng like queryset = Tradegroup.objects.filter(owner=self.request.user) in native django, but was wondering how I could achieve this here.

This should actually work by overriding the get_queryset method. Simply add this method to your ListAPIView and it should work.

class TradingGroupList(generics.ListAPIView):
    
    serializer_class = TradeGroupSerializer
    name = 'tradegroup-list'

    def get_queryset(self)
        return Tradegroup.objects.all().filter(owner=self.request.user)

I hope this works for you. If you have a problem with it just give me a comment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM