jan-seins
jan-seins

Reputation: 1293

Add url to API response on serializers.Serializer

I have a django-application with the followin files

models.py

from datetime import datetime

class Comment(object):
    def __init__(self, email, content, created=None):
        self.email = email
        self.content = content
        self.created = created or datetime.now()

serializers.py

from rest_framework import serializers

class CommentSerializer(serializers.Serializer):
    email = serializers.EmailField()
    content = serializers.CharField(max_length=200)
    created = serializers.DateTimeField()
    url = serializers.CharField(source='get_absolute_url', read_only=True)

in views.py I now define a a ViewSet to return the serialized results. In this class I define a list of comments

views.py

from rest_framework import viewsets
from .serializers import *
from .models import Comment
from rest_framework.response import Response


class CommentViewSet(viewsets.ViewSet):
    lc = [Comment(email='[email protected]', content='hallo mike'),
          Comment(email='[email protected]', content='hallo jan'),
          Comment(email='[email protected]', content='hallo niklas')]

    def list(self, request):
        serializer = CommentSerializer(self.lc, many=True)
        return Response(serializer.data)

    def retrieve(self, request, pk=None):
        user = self.lc[int(pk)]
        serializer = CommentSerializer(user)
        return Response(serializer.data)

When I now call the api (http://127.0.0.1:8000/comments/?format=json) I get the following result

[
  {
    "email": "[email protected]",
    "content": "hallo mike",
    "created": "2019-08-16T16:53:56.371890Z"
  },
  {
    "email": "[email protected]",
    "content": "hallo jan",
    "created": "2019-08-16T16:53:56.371890Z"
  },
  {
    "email": "[email protected]",
    "content": "hallo niklas",
    "created": "2019-08-16T16:53:56.371890Z"
  }
]

In this response I would have hoped to see a url for each dataset. The error ist probably thats for url = serializers.CharField(source='get_absolute_url', read_only=True) the source is undefined in the Comment class. However I have no clue how to achieve this. Any help is appreciated.

Upvotes: 1

Views: 243

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477794

You need to define a get_absolute_url method [Django-doc] on your model, like:

# app/models.py

from django.db import models
from django.urls import reverse

class Comment(models.Model):
    email = models.EmailField()
    content = models.CharField(max_length=128)
    created = models.DateTimeField(auto_now_add=True)

    def get_absolute_url(self):
        return reverse('name-of-view', kwargs={'pk': self.pk})

Here 'name-of-view' is the name of the view you defined, for example in your urls.py, and the kwargs=... is given a dictionary that maps the values for the corresponding URL path parameters.

Upvotes: 1

Related Questions