0

The goal I am trying to achieve is querying for all of a specific Model that has a ForeignKey relationship with an individual instance of another Model.

I'm curious what the proper way of routing an API call would look like. The thought/hope is that it will look similar to:

'/api/v1/devices/<id>/breadcrumbs'

I am new to Django Rest Framework and am unsure of what to do here. I have created basic Viewsets like below:

class DeviceViewSet(viewsets.ModelViewSet):
    queryset = Device.objects.all()
    serializer_class = DeviceSerializer

class BreadcrumbViewSet(viewsets.ModelViewSet):
    queryset = Breadcrumb.objects.all()
    serializer_class = BreadcrumbSerializer

As well as the basic routes:

router.register(r'devices', DeviceViewSet)
router.register(r'breadcrumbs', BreadcrumbViewSet)

And the Breadcrumb model:

class Breadcrumb(models.Model):
    timestamp = models.DateTimeField(
        auto_now_add=True,
        editable=False,
        null=False,
        blank=False
    )
    device = models.ForeignKey(
        Device, 
        on_delete=models.CASCADE
    )

But don't know how to extend this to the logic I am looking to achieve.

Bonteq
  • 777
  • 7
  • 24

1 Answers1

1

There is a project that can be of interest for you, here is the official documentation.

This way you can create urls.py like:

from rest_framework_nested import routers

device_router = routers.SimpleRouter()
device_router.register(r'devices', DeviceViewSet)

device_breadcrumbs_router = routers.NestedSimpleRouter(device_router, r'breadcrumbs', lookup='breadcrumb')
device_breadcrumbs_router.register(r'breadcrumbs',BreadcrumbViewSet)

And inside BreadcrumbViewSet override:

def get_queryset(self):
    device_id = self.kwargs.get('device',None)

    return Breadcrumb.objects.filter(device_id=device_id)

The same way you override 'get_queryset' you can get the same result on 'perform_create', 'perform_update', etc.

Ruben
  • 129
  • 5
  • Thank you. I haven't had time to try this out, but I'll mark as accepted if and when it works! – Bonteq Mar 15 '19 at 18:05
  • I am getting a RuntimeError('parent registered resource not found') after attempting your code example. The exception is on line 80 of rest_framework_nested/routers.py. – Bonteq Mar 16 '19 at 21:53
  • Ended up creating an additional thread to display the code and hopefully showcase the problem more in depth. It's at: https://stackoverflow.com/questions/55202454/drf-nested-routers-runtimeerrorparent-registered-resource-not-found – Bonteq Mar 16 '19 at 23:29