Imagine there's a Django Library Model (which requires a name and address) which looks like this:
class Library(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=100)
And there's a Book model where each book is defined by its title and author, like this:
class Book(models.Model):
title = models.CharField(max_length=50)
author = models.CharField(max_length=50)
I'm using angular.js on the frontend with Django Rest Framework (DRF) on the backend. I would like to create a form where the user can enter the Library details (i.e. name and address) and one or several books (using multiple book forms).
The problem that I'm facing is how to create a serializer and the right view to handle this data, which in its JSON form should like similar to this:
{
'name': 'The Great Library',
'address': 'Babylon',
'books': [
{'title':'ABC', 'author':'Whatever'},
{'title':'Django', 'author':'BlaBla'},
{'title':'Angular', 'author':'BlaBlaBla'},
...
]
}
Here are my serializers which should achieve this:
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('title', 'author')
class LibrarySerializer(serializers.ModelSerializer):
books = BookSerializer(many=True)
class Meta:
model = Company
fields = ('name', 'address', 'id', 'books')
def create(self, validated_data):
books_data = validated_data.pop('books')
library = Library.objects.create(**validated_data)
for book in books_data:
Book.objects.create(library = library, **book)
return library
The problem is the right view.. I've tried the approach in this question but since my form has additional fields (library details) apart from several books (several instances of the same form) this does not work(there's a list required, however my data is a dictionary with a list - like shown in the JSON example above).
Which Django Rest Framework view would be the best to solve this? I have difficulties understanding this so any help much appreciated!