I have a serialised model (Job) which I am using with datatables. The "Job" model is related to another model (Board) and here is where my problem is. I followed the doc here to filter jobs that are related to the "Board" model which is currently being viewed, but I can't get it to work as intended.
models.py
class Board(models.Model):
name = models.CharField(_('board name'), max_length=256)
slug = models.SlugField(_('unique url'), null=True, blank=True)
...
class Job(models.Model):
board = models.ForeignKey(Board, on_delete=models.CASCADE, verbose_name=_('board'))
...
views.py
class JobDataTablesViewSet(viewsets.ModelViewSet):
queryset = Job.objects.all().order_by('-date_posted')
serializer_class = JobDatatablesSerializer
filter_backends = (DatatablesFilterBackend,)
filterset_class = JobGlobalFilter
def get_queryset(self):
slug = self.kwargs['slug']
queryset = Job.objects.filter(board__slug=slug)
return queryset
urls.py
path('<slug:slug>/', views.BoardPublicView.as_view(), name='public-board')
For anyone with a similar issue, kindly take a look at alanjds/drf-nested-routers. This is what I used and it worked perfectly.
Here is an overview of what I did.
After installing the package with
pip install drf-nested-routers.According to the docs,
In my app
urls.pyfile, I created parent and child routersThen in my
serializers.py, I created aHyperlinkedModelSerializerI went on to my
views.pyto create my viewsets and added theget_querysetparamsOnce you do these, you should be able to access your APIs via
Now, because of my peculiar need (I wanted to use this on datatables to filter related objects), I added the URLs of my APIs to the head of my
base.htmlso that the URLs can be loaded dynamically since I can't load such in my javascript fileAnd in my
main.pyfile, I did the following