Search code examples
djangopython-3.xmongodb-querymongoengineflask-mongoengine

Change Document 'objects' property to 'query'


I'm trying to change the document 'objects' property to 'query'. It's more intuitive since one is querying the database. Like; Collection.query.find() Instead of; Collection.objects.find() I have tried setting a query attribute to my Collection model like;

class Collection(Document):
    def __setattr__(self, key, objects):
        self.__dict__['query'] = self.objects

But on checking the type it returns a class of the QueryManager instead of Queryset like;

>>>print(type(Collection.query))
<'class' mongoengine.queryset.queryset.QueryManager >

Instead of;

>>>print(type(Collection.query))
<'class' mongoengine.queryset.queryset.Queryset >

Could someone offer a solution ?


Solution

  • Define an abstract Document class and within it define a custom QuerySet manager using queryset_manager wrapper. Inherit the abstract class as a Base class for all other subsequent Document classes.

    from mongoengine.document import Document
    from mongoengine.queryset import queryset_manager
    
    class BaseDocument(Document):
        meta = {'abstract': True}
        @queryset_manager
        def query(self, queryset):
            return queryset
    
    class Foo(BaseDocument):
        ...
    

    To query use Foo.query.* which is more intuitive instead of the default Foo.objects.*. Displaying the type will return <class 'mongoengine.queryset.queryset.Queryset'> as expected.