Generics.ListCreateAPIView(Django Rest Framework)

时间:2019-03-03 13:58:36

标签: django rest django-rest-framework

ViewClass(会话列表):

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'
    )

会话模型:

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',)

我正在使用(django.contrib.auth.models.User)创建我的用户。

如何过滤查询器集以仅获取属于已登录用户的会话列表?

1 个答案:

答案 0 :(得分:0)

与标准Django通用视图一样,您需要定义get_queryset

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