Search code examples
djangomongodbpymongopymodm

PyMODM - Find Document(s)


I'm using PyModm as an ORM layer for MongoDB for my Django CRUD app.

I created a MongoModel as in so:

class Book(MongoModel):
    title = fields.CharField(primary_key=True)
    author = fields.CharField()

To create and update documents the pymodm API is really good, but I couldn't find an easy way to retrieve one or more documents, as Book.object.all() returns a QuerySet that seems to be only Json-serializable when iterating over it.

So the workaround I found is

books = []
for book in Book.objects.all():
    books.append({
        'title': book.title,
        'author': contact.author
    })
return JsonResponse(books)

And for retrieving one book by it's primary-key:

for book in Book.objects.raw({'_id': title}):
    book = {
        'author': book.author,
        'title': book.title
    }
return JsonResponse(book)

However, this seems not a very sufficient nor pretty way. Is there any better way?


Solution

  • Maybe values() will help:

    books = list(Book.objects.values().all())
    book = Book.objects.values().get({'_id': user_id})