I've just gone through the Django-Rest-Framework (DRF) tutorial and tried to adapt it to a simple photos app I am working on with models Album
and Photo
in a M-2-M relationship: an album can have many photos, and a photo can be in many albums. The db has tables myapp_album
, myapp_photo
and myapp_album_photos
, as you'd expect.
But what I want is to be able to create albums and photos independent of each other and then to create the relations between them. I can do that easily in the shell with the photo.add(album)
, etc. but it's not clear to me how to do this via the generated DRF routes.
The problem is that using the terse DRF abstractions that I gleaned from the tutorial (using ModelSerializer, viewsets, etc.), I only end up with routes to /albums
and /photos
, and it's not clear to me how to create a route (or how otherwise) to associate existing photos with existing albums.
Could someone please help clarify the situation? Thanks
### models.py
class Photo(models.Model):
title = models.CharField(max_length=100, blank=True)
caption = models.TextField(blank=True)
datetime = models.DateTimeField(auto_now_add=False, blank=False)
filename = models.CharField(max_length=100, blank=False)
class Album(models.Model):
name = models.CharField(max_length=100, blank=False, default='')
description = models.TextField()
photos = models.ManyToManyField(Photo)
### serializers.py
class AlbumSerializer(serializers.ModelSerializer):
class Meta:
model = Album
fields = ['id', 'name', 'description']
class PhotoSerializer(serializers.ModelSerializer):
class Meta:
model = Photo
fields = ['id', 'title', 'caption', 'datetime', 'filename']
### views.py
class AlbumViewSet(viewsets.ModelViewSet):
queryset = Album.objects.all()
serializer_class = AlbumSerializer
class PhotoViewSet(viewsets.ModelViewSet):
queryset = Photo.objects.all()
serializer_class = PhotoSerializer