+
from django.db import models
class Actor(models.Model):
first_name = models.CharField(max_length=64, blank=False, null=False)
last_name = models.CharField(max_length=64, blank=False, null=False)
date_of_birth = models.DateField(blank=False, null=False)
@property
def full_name(self):
return f'{self.first_name} {self.last_name}'
class Movie(models.Model):
title = models.CharField(max_length=256, blank=False, null=False)
actors = models.ManyToManyField(Actor, related_name='movies')
Models:
from rest_framework import serializers
from .models import Actor, Movie
class ActorSerializer(serializers.ModelSerializer):
class Meta:
model = Actor
fields = ('id', 'full_name', 'date_of_birth')
class MovieSerializer(serializers.ModelSerializer):
actors = ActorSerializer(many=True, read_only=True)
class Meta:
model = Movie
models = ('id', 'title', 'actors')
serializers:
from rest_framework import viewsets
from .models import Movie
from .serializers import MovieSerializer
class MovieViewSet(viewsets.ModelViewSet):
queryset = Movie.objects.all()
serializer_class = MovieSerializer
VIEWS:
URLS:
from django.urls import path
from rest_framework import routers
from .views import MovieViewSet
movies_router = routers.DefaultRouter()
movies_router.register(r'movies', MovieViewSet, base_name='api_movies')
urlpatterns = movies_router.urls
GET api/v1/movies
{
{
"id": 1,
"title": "Bohemian Rhapsody",
"actors": [
{
"id": 1,
"full_name": "Rami Malek",
"date_of_birth": "12-05-1981"
},
{
"id": 2,
"full_name": "Gwilym Lee",
"date_of_birth": "24-11-1983"
}
]
},
{
"id": 2,
"title": "A Star Is Born",
"actors": [
{
"id": 1,
"full_name": "Lady Gaga",
"date_of_birth": "28-03-1986"
},
{
"id": 2,
"full_name": "Bradley Cooper",
"date_of_birth": "05-01-1975"
}
]
}
}
DEMO
DRF
By Ventsislav Tashev
DRF
Django REST Framework overview presentation
- 656