Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest queryset filter by url parameter

I need to filter queryset in ListAPIView depending on url parameter. Basically, application lists all attendees (User) of an event with a call to API like /events/:id/attendees/

You can find serializers, models, urls and views below. I also wonder any other practices to do such end-point implementation in 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)
like image 617
brsbilgic Avatar asked Aug 23 '14 09:08

brsbilgic


People also ask

How do I filter Queryset in Django REST framework?

The simplest way to filter the queryset of any view that subclasses GenericAPIView is to override the . get_queryset() method. Overriding this method allows you to customize the queryset returned by the view in a number of different ways.

How do you use DjangoFilterBackend?

The DjangoFilterBackend class is used to filter the queryset based on a specified set of fields. This backend class automatically creates a FilterSet (django_filters. rest_framework. FilterSet) class for the given fields.

What is Queryset in Django REST framework?

queryset - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set read_only=True . many - If applied to a to-many relationship, you should set this argument to True .


1 Answers

You can access the url parameter in your view with self.kwargs['parameter_name'] ( http://www.django-rest-framework.org/api-guide/filtering#filtering-against-the-url ). So the simplest solution would be

def get_queryset(self):
    return Attendee.objects.filter(event=self.kwargs['pk'])
like image 192
Zorba Avatar answered Oct 22 '22 10:10

Zorba