Django Rest查询集按url参数过滤

时间:2014-08-23 09:19:31

标签: django django-rest-framework

我需要根据url参数过滤ListAPIView中的查询集。基本上,应用程序通过调用API /events/:id/attendees/

列出事件的所有与会者(用户)

您可以在下面找到序列化程序,模型,网址和视图。我也想知道在Django REST中进行这种端点实现的任何其他实践

**serializers.py**
class AttendeeSerializer(serializers.ModelSerializer):
    user = UserSerializer()

    class Meta:
        model = Attendee
        fields = ('user', 'status')


**views.py**
class EventAttendeeList(generics.ListAPIView):
    queryset = Attendee.objects.all()
    serializer_class = AttendeeSerializer
    #permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

    def get_queryset(self):
        # It should filter attendees by event_id posted in URL
        return Attendee.objects.all()

**urls.py**

url(r'^events/(?P<pk>[0-9]+)/attendees/$', views.EventAttendeeList.as_view()),


**models.py**
class Event(models.Model):
    name = models.CharField(max_length=500, blank=True)
    attendees = models.ManyToManyField(settings.AUTH_USER_MODEL, through='Attendee', related_name='attendees_event')


class Attendee(models.Model):
    event = models.ForeignKey(Event, related_name="a_event")
    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="a_user")
    requested_on = models.DateTimeField(default=timezone.now)

1 个答案:

答案 0 :(得分:20)

您可以使用self.kwargs['parameter_name']http://www.django-rest-framework.org/api-guide/filtering#filtering-against-the-url)访问视图中的url参数。所以最简单的解决方案是

def get_queryset(self):
    return Attendee.objects.filter(event=self.kwargs['pk'])