How may I convert a Many to Many field into JSON Format in Django

I am working with APIs based in REST Architecture. I know Django has a framework to work with this APIs but my homework is do it from scratch. I got an API of a movies site where users can go and search information about a bunch of movies and i am trying to get the data into JSON format from the model Movie which has a Many-to-Many relationship whith the Actor model. I am using Class-based views for this.

The code from my models.py and views.py files is nested below:

    class Actor(models.Model):
    full_name = models.CharField(max_length=125)
    role = models.CharField(max_length=125)

    def __str__(self):
        return self.full_name


class Movie(models.Model):
    ACTION = 'AC'
    DRAMA = 'DR'
    COMEDY = 'CM'
    SCIENCE_FICTION = 'SF'
    THRILLER = 'TR'
    RELIGIOUS = 'RG'

    GENRE_CHOICES = [

        (ACTION, 'Accion'),
        (DRAMA, 'Drama'),
        (COMEDY, 'Comedy'),
        (SCIENCE_FICTION, 'Ciencia Ficcion'),
        (THRILLER, 'Triler'),
        (RELIGIOUS, 'Religioso')
    ]

title = models.CharField(max_length=155, blank=False)
synopsis = models.TextField(max_length=1000, blank=True)
genre = models.CharField(max_length=100, choices=GENRE_CHOICES, default='', blank=False)
tag = models.JSONField(default=dict, blank=True)
actors = models.ManyToManyField(Actor, related_name='movies', blank=True)

def __str__(self):

views.py

    from django.views import View
from django.http.response import JsonResponse
from .models import Movie
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
import json


class MovieView(View):

    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, **kwargs)

    def get(self, request, pk=0):
        """
        Return the list of all movies, or a single movie
        :param pk:
        :param request:
        :return:
        """
        if pk > 0:
            movies = list(Movie.objects.filter(pk=pk).values())
            if len(movies) > 0:
                movie = movies[0]
                data = {'message': "Success", 'movie': movie}
            else:
                data = {'message': "Movie not found... "}
            return JsonResponse(data)
        else:

            movies = list(Movie.objects.values('title', 'synopsis', 'genre', 'actors__full_name').order_by('pk'))
            if len(movies) > 0:
                data = {'message': "Success", 'movies': movies}
            else:
                data = {'message': "Movies not found ..."}
            return JsonResponse(data)

    def post(self, request):
        """
        Create a new movie
        :param request:
        :return:
        """
        json_data = json.loads(request.body)

        Movie.objects.create(title=json_data['title'], synopsis=json_data['synopsis'], genre=json_data['genre'],
                             tag=json_data['tag'], actors=json_data['actors'])
        data = {'message': "Success"}
        return JsonResponse(data)

    def put(self, request, pk):
        """
        Update a single movie
        :param request:
        :param pk:
        :return:
        """
        json_data = json.loads(request.body)
        movies = list(Movie.objects.filter(pk=pk).values())
        if len(movies) > 0:
            movie = Movie.objects.get(pk=pk)
            movie.title = json_data['title']
            movie.synopsis = json_data['synopsis']
            movie.genre = json_data['genre']
            movie.tag = json_data['tag']
            movie.save()
            data = {'message': "Success"}
        else:
            data = {'message': "Movie not found ..."}
        return JsonResponse(data)

    def delete(self, request, pk):
        movies = list(Movie.objects.filter(pk=pk).values())
        if len(movies) > 0:
            Movie.objects.filter(pk=pk).delete()
            data = {'message': "Success"}
        else:
            data = {'message': "Movie not found ..."}
        return JsonResponse(data)
Back to Top