aqra youdef
aqra youdef

Reputation: 27

Generics.ListCreateAPIView (Django Rest Framework)

ViewClass (SessionList):

class SessionList(generics.ListCreateAPIView):
    throttle_scope = 'session'
    throttle_classes = (ScopedRateThrottle,)
    #I want to get the session list of speifc user
    #for ex: queryset = Session.objects.all.filter(id=1)
    queryset = Session.objects.all()
    serializer_class = SessionSerializer
    name = 'session-list'
    filter_class = SessionFilter
    ordering_fields = (
        'distance_in_miles',
        'speed'
    )

Session Model:

class Session(models.Model):

    distance_in_miles = models.FloatField()
    speed = models.FloatField()
    owner = models.ForeignKey(
        'auth.User',
        related_name='Session',
        on_delete=models.CASCADE)

    class Meta:
        ordering = ('-distance_in_miles',)

I'm using (django.contrib.auth.models.User) to create my users.

How to filter the quyerset to get only the list of sessions that belong to the logged in user?

Upvotes: 1

Views: 1026

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 600059

As with a standard Django generic view, you need to define get_queryset.

class SessionList(generics.ListCreateAPIView):
    ...
    def get_queryset(self):
        return Session.objects.filter(owner=self.request.user)

Upvotes: 2

Related Questions