1

Im still new with Django Rest Framework, I want to filter the queryset using an URL parameter.

Here's my models.py:

class Offre(models.Model):          
    title = models.CharField(max_length=100, blank=True, default=0)
    secteur = models.CharField(max_length=50, null=True)
    idRecruteur = models.ForeignKey(Recruteur,verbose_name = "idRecruteur", on_delete=models.CASCADE, default=None)
    def __str__(self):
        return "Offre: {}".format(self.title)   

Here's what i did in urls.py:

router = DefaultRouter();
router.register(r'OffresByRecruteur/(?P<idRecruteur_id>\d+)/$', OffreRecruteurViewSet, base_name='inoutreports')
urlpatterns = router.urls

Finally api.py:

class OffreRecruteurViewSet(ModelViewSet):
    queryset = Offre.objects.all()
    serializer_class = OffreSerializer

    def get_queryset(self, *args, **kwargs):
        return self.queryset.filter(idRecruteur_id=self.request.GET.get('idRecruteur_id'))

This generates

Using the URLconf defined in djangular.urls, Django tried these URL patterns, in this order: 
   ^scrumboard/ ^OffresByRecruteur/(?P<idRecruteur_id>\d+)/$/$ [name='inoutreports-list']
   ^scrumboard/ ^OffresByRecruteur/(?P<idRecruteur_id>\d+)/$\.(?P<format>[a-z0-9]+)/?$ [name='inoutreports-list']
   ^scrumboard/ ^OffresByRecruteur/(?P<idRecruteur_id>\d+)/$/(?P<idRecruteur>[^/.]+)/$ [name='inoutreports-detail']
   ^scrumboard/ ^OffresByRecruteur/(?P<idRecruteur_id>\d+)/$/(?P<idRecruteur>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='inoutreports-detail']
The current path, scrumboard/OffresByRecruteur/1/, didn't match any of these.

What am I doing wrong ?

1 Answer 1

2

Your regex for registering the viewset should not end with /$. Rest framework will add the slash by default, and you don't want the dollar because it matches the end of the string.

router.register(r'OffresByRecruteur/(?P<idRecruteur_id>\d+)/', OffreRecruteurViewSet, base_name='inoutreports')

Secondly, when you get the queryset, you should get idRecruteur_id from self.kwargs. You would use self.request.GET to fetch from the querystring, e.g. if the URL was /scrumboard/OffresByRecruteur/?idRecruteur_id=1.

def get_queryset(self, *args, **kwargs):
    return self.queryset.filter(idRecruteur_id=self.kwargs['idRecruteur_id']))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.