Use the value captured from URL with DRF Serializer

2019/03/30 22:00

※ 商品のリンクをクリックして何かを購入すると私に少額の報酬が入ることがあります【広告表示】

I don't know how to do it in Django REST Framework, so I write an idea.

Code is here.

Comment can be added to Todo

  from django.db import models


  class Todo(models.Model):
      headline = models.CharField(max_length=200)
      content = models.TextField()
      created_at = models.DateTimeField(auto_now_add=True)


  class Comment(models.Model):
      todo = models.ForeignKey(Todo, on_delete=models.CASCADE)
      title = models.CharField(max_length=200)
      body = models.TextField()
      created_at = models.DateTimeField(auto_now_add=True)

      class Meta:
          unique_together = (('todo', 'title'),)

The definition of urls.py is as follows

The parent Todo id of the Comment is specified in the URL.

  router.register(
      r'todos/(?P<todo_id>\d)/comments',
      CommentViewSet,
      basename='todo_comment',
  )

Pass todo_id via ViewSet.get_serializer_context

Pass to Serializer via get_serializer_context of ViewSet.

  def get_serializer_context(self):
      context = super().get_serializer_context()
      context['todo_id'] = self.kwargs['todo_id']
      return context

Set todo_id view ModelSerializer.to_internal_value

  def to_internal_value(self, data):
      values = super().to_internal_value(data)
      values['todo_id'] = self.context['todo_id']
      return values

I feel right as a method usage, todo_id validation is omitted for simplicity.

Prev Entry

Next Entry