Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework: Embed Viewset Inside Viewset

I have the following two Django models (simplified for this example).

class Participant(models.Model):
    name = models.CharField()
    study_id = models.IntegerField()
    ... 
    # Lots of other fields

class Message(models.Model):
    text = models.CharField()
    participant = models.ForeignKey('Participant')

Using Django Rest Framework I have set up a ModelSerializer and ModelViewSet for each model. Using the @detail_route and @list_route decorators I have set up the following URLs.

/api/participant/ (GET,POST for list and create)
/api/participant/:study_id (GET,PUT for retrieve and update)
/api/participant/:study_id/messages (GET for list POST to send message)

I would like to add the following url for changing message meta data. This will make working with the API much easier in restangular

/api/participant/:study_id/messages/:msg_id (PATCH partial update of message)

It would be nice to have a way to embed a Message ViewSet inside the Participant since this would make the logic for GET and POST on messages simpler as well. Is this possible? If not how can I pass the msg_id to a @detail_rouet on messages?

like image 427
fizzyh2o Avatar asked Jun 16 '26 03:06

fizzyh2o


1 Answers

This is a case of nested routers. Beside the one already mentioned, I will name https://github.com/chibisov/drf-extensions

Personally, I've used Restangular with drf-extensions. Comes with caching support.

Two hints on how to enable nested routing:

  • you must declare in your viewset the model on which it operates
  • you must follow the nested router definition correctly.
like image 58
Roba Avatar answered Jun 17 '26 18:06

Roba