Django Rest Framework: Implementing Many-to-Many r

2019-09-06 23:29发布

问题:

I'm using the Django Rest Framework to create a custom API for my Movies model which is defined as follows:

models.py

from django.db import models


class Genres(models.Model):
    genre = models.CharField(max_length = 128, unique = True)

class Movies(models.Model):
    popularity = models.FloatField()
    director = models.CharField(max_length = 128)
    genres = models.ManyToManyField(Genres, related_name = 'movies')
    imdb_score = models.FloatField()
    movie_name = models.CharField(max_length = 500)

Now, in my application, each genre can have multiple movie instances and vice versa. As a result, there is a Many-to-Many relationship between the Genres model and the Movies model. I want to allow the admin to chose multiple genres for a particular movie while posting new Movies instances at the API endpoint.

serializers.py

from shoppy.models import Movies, Genres
from rest_framework import serializers


class GenresSerializer(serializers.ModelSerializer):

    class Meta:
        model = Genres

class MoviesSerializer(serializers.ModelSerializer):


    class Meta:
        model = Movies
        fields = ('popularity', 'director', 'imdb_score', 'genres',
                        'movie_name')

views.py

from shoppy.models import Movies
from rest_framework import viewsets
from shoppy.serializers import MoviesSerializer


class MovieViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = Movies.objects.all()
    serializer_class = MoviesSerializer

urls.py

from django.conf.urls import url, include
from rest_framework import routers
from shoppy import views

router = routers.DefaultRouter()
router.register(r'movies', views.MovieViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

However, I'm encountering the following error:

Exception Type: OperationalError at /movies/
Exception Value: no such table: shoppy_genres

What seems to be wrong with my code?