Using Django serializer Fields

class Album(models.Model):
album_name = models.CharField(max_length=100)
artist = models.CharField(max_length=100)

class Track(models.Model):
album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE)
order = models.IntegerField()
title = models.CharField(max_length=100)
duration = models.IntegerField()

class Meta:
unique_together = ['album', 'order']
ordering = ['order']

def __str__(self):
return '%d: %s' % (self.order, self.title)

StringRelatedField:

class AlbumSerializer(serializers.ModelSerializer):
tracks = serializers.StringRelatedField(many=True)

class Meta:
model = Album
fields = ['album_name', 'artist', 'tracks']
#Output:{
'album_name': 'Things We Lost In The Fire',
'artist': 'Low',
'tracks': [
'1: Sunflower',
'2: Whitetail',
'3: Dinosaur Act',
...
]
}

SlugRelatedField:

class AlbumSerializer(serializers.ModelSerializer):
tracks = serializers.SlugRelatedField(
many=True,
read_only=True,
slug_field='title'
)

class Meta:
model = Album
fields = ['album_name', 'artist', 'tracks']
#Output:{
'album_name': 'Dear John',
'artist': 'Loney Dear',
'tracks': [
'Airport Surroundings',
'Everything Turns to You',
'I Was Only Going Out',
...
]
}

HyperlinkedIdentityField:

class AlbumSerializer(serializers.HyperlinkedModelSerializer):
track_listing = serializers.HyperlinkedIdentityField(view_name='track-list')

class Meta:
model = Album
fields = ['album_name', 'artist', 'track_listing']
#Output{
'album_name': 'The Eraser',
'artist': 'Thom Yorke',
'track_listing': 'http://www.example.com/api/track_list/12/',
}

Nested relationships:

class TrackSerializer(serializers.ModelSerializer):
class Meta:
model = Track
fields = ['order', 'title', 'duration']

class AlbumSerializer(serializers.ModelSerializer):
tracks = TrackSerializer(many=True, read_only=True)

class Meta:
model = Album
fields = ['album_name', 'artist', 'tracks']
#Output>>> album = Album.objects.create(album_name="The Grey Album", artist='Danger Mouse')
>>> Track.objects.create(album=album, order=1, title='Public Service Announcement', duration=245)
<Track: Track object>
>>> Track.objects.create(album=album, order=2, title='What More Can I Say', duration=264)
<Track: Track object>
>>> Track.objects.create(album=album, order=3, title='Encore', duration=159)
<Track: Track object>
>>> serializer = AlbumSerializer(instance=album)
>>> serializer.data
{
'album_name': 'The Grey Album',
'artist': 'Danger Mouse',
'tracks': [
{'order': 1, 'title': 'Public Service Announcement', 'duration': 245},
{'order': 2, 'title': 'What More Can I Say', 'duration': 264},
{'order': 3, 'title': 'Encore', 'duration': 159},
...
],
}
mkdir djangoAlbums
cd djangoAlbums
pipenv shell
pipenv install django djangorestframework
django-admin startproject album_project .
python manage.py startapp album_app
#album_project/settings.py...INSTALLED_APPS = ['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'album_app.apps.AlbumAppConfig',
]...
#album_app/models.py
from django.db import modelsclass Album(models.Model):
album_name = models.CharField(max_length=100)
artist = models.CharField(max_length=100)
def __str__(self):
return self.album_name

class Track(models.Model):
album = models.ForeignKey(Album, related_name='tracks',on_delete=models.CASCADE)
order = models.IntegerField()
title = models.CharField(max_length=100)
duration = models.IntegerField()
class Meta:
unique_together = ['album','order']
ordering = ['order']
def __str__(self):
return '%d: %s' % (self.order, self.title)
#album_app/serializers.pyfrom rest_framework import serializers
from .models import Album, Track
class AlbumSerializer(serializers.ModelSerializer):
class Meta:
model = Album
fields = (
'url',
'album_name',
'artist',
)
class AlbumDetailSerializer(serializers.ModelSerializer):
tracks = serializers.StringRelatedField(many=True)
class Meta:
model = Album
fields = (
'url',
'album_name',
'artist',
'tracks',
)
#album_app/views.pyfrom rest_framework import generics
from .models import Album, Track
from .serializers import AlbumSerializer ,AlbumDetailSerializer
class AlbumList(generics.ListCreateAPIView):
queryset = Album.objects.all()
serializer_class = AlbumSerializer
name = 'album-list'
class AlbumDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Album.objects.all()
serializer_class = AlbumDetailSerializer
name = 'album-detail'
#album_app/urls.pyfrom django.conf.urls import url
from . import views
urlpatterns = [
url(r'^albums/$',
views.AlbumList.as_view(),
name=views.AlbumList.name
),
url(r'^albums/(?P<pk>[0-9]+)$',
views.AlbumDetail.as_view(),
name=views.AlbumDetail.name),
]
#album_app/admin.pyfrom django.contrib import admin
from .models import Album, Track
admin.site.register(Album)
admin.site.register(Track)
from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include

urlpatterns = [
path('admin/', admin.site.urls),
url(r'^', include('album_app.urls')),
]
python manage.py makemigrations album_app
python manage.py migrate
#This allowed us to use admin panel
python manage.py createsuperuser
python manage.py runserver

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store