How to serialize EmbeddedDocumentListField in Django REST Framework Mongoengine?

Viewed 2085

I am sending an API post request with the following in the request body (converted to JSON string) to be serialized as the BookCollection document with books persisted as a list of embedded documents:

{
    'author': '<author_id>',
    'books': [
        {
            'title': 'Grapes of Wrath',
            'note': 'More to be ordered.',
            'created': '2016-03-11T17:59:01.054Z'
        }
    ]
}

views.py:

def post(self, request, *args, **kwargs):
    serializer = BookCollectionSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors,
                    status=status.HTTP_400_BAD_REQUEST)

models.py:

class Book(EmbeddedDocument):
    title = StringField(required=True, max_length=50)
    note = StringField(required=False, max_length=2000)
    created = DateTimeField(required=True,
                            default=datetime.datetime.now())


class BookCollection(Document):
    author = ReferenceField(Author, required=True)
    books = EmbeddedDocumentListField(Book, required=False)

serializers.py

class BookSerializer(EmbeddedDocumentSerializer):

    class Meta:
        model = Book
        depth = 2


class BookCollectionSerializer(DocumentSerializer):
    author = ReferenceField(Author)
    books = BookSerializer(Book, many=True)

    class Meta:
        model = BookCollection
        depth = 2

    def create(self, validated_data):
        books = validated_data.pop('books')
        book_collection = BookCollection.objects.create(**validated_data)
        book_collection.books = []
        for book in books:
            book_collection.books.append(book)
        book_collection.save()
        return book_collection

When I run the post request, the BookCollection object does get persisted; however, the books list (a list of embedded documents) is not persisted inside the BooksCollection. It's just set to a blank list []. What am I doing wrong here? I also tried to remove the logic from the create() method, but that didn't help. Thank you!

1 Answers
Related