MongoEngine / mongoengine

A Python Object-Document-Mapper for working with MongoDB
http://mongoengine.org
MIT License
4.23k stars 1.23k forks source link

Issue with distinct() operation on ListField of EmbeddedDocuments #470

Closed DirectX closed 10 years ago

DirectX commented 11 years ago

MongoEngine possible bug (tested on 0.8.4): the result of distinct() operation on ListField of EmbeddedDocuments is a list of dictionaries rather than list of EmbeddedDocuments as it works in previous versions of library. Here is an example.

from mongoengine import *

class Author(EmbeddedDocument):
    name = StringField()

class Book(Document):
    title = StringField()
    authors = ListField(EmbeddedDocumentField(Author))

def populate():
    Book.drop_collection()

    mark_twain = Author(name="Mark Twain")
    john_tolkien = Author(name="John Ronald Reuel Tolkien")

    book = Book(title="Tom Sawyer")
    book.authors.append(mark_twain)
    book.save()

    book = Book(title="The Lord of the Rings")
    book.authors.append(john_tolkien)
    book.save()

    book = Book(title="The Stories")
    book.authors.append(mark_twain)
    book.authors.append(john_tolkien)
    book.save()

if __name__ == "__main__":
    connect('test')
    populate()

    books = Book.objects()

    print "\nAll books:"

    print "\n".join(map(lambda b: b.title + " by " + " and ".join(map(lambda a: a.name, b.authors)), books))

    print "\nUnique authors (unexpected output):"

    authors = books.distinct("authors")

    for author in authors:
      print author["name"] + " (" + author.__class__.__name__ + ")"

    print "\nUnique authors (expected output):"

    authors = map(lambda a: Author(**a), authors)

    for author in authors:
      print author.name + " (" + author.__class__.__name__ + ")"

The output:

All books:
Tom Sawyer by Mark Twain
The Lord of the Rings by John Ronald Reuel Tolkien
The Stories by Mark Twain and John Ronald Reuel Tolkien

Unique authors (unexpected output):
Mark Twain (BaseDict)
John Ronald Reuel Tolkien (BaseDict)

Unique authors (expected output):
Mark Twain (Author)
John Ronald Reuel Tolkien (Author)
rozza commented 11 years ago

marking for 0.9

rozza commented 11 years ago

Sorry 0.8.x

raonyguimaraes commented 10 years ago

bump

rozza commented 10 years ago

Please don't bump its rude! Pull requests are the polite way to do it! ;)

All done and ready for 0.8.5