Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Heterogeneous Lists in Python MongoEngine

does MongoEngine supports having different data types in a list? For example, I'd like a ListField() to store IntField() as well as StringField(). Is there a way to do this in MongoEngine?

like image 616
dev Avatar asked Aug 28 '26 03:08

dev


1 Answers

The ListField does not enforce a datatype unless you ask it to. However if you do then it has to be a single datatype at the moment. For example

This works:

import mongoengine as mdb
class Stuff(mdb.Document):
    things = mdb.ListField()

s = Stuff(things=['1',2,[4,5]])
s.save()

this throws TypeError as it is enforcing a datatype:

import mongoengine as mdb
class Stuff(mdb.Document):
    things = mdb.ListField(mdb.IntField())

s = Stuff(things=['1',2,[4,5]])
s.save()

this throws AttributeError as it is expecting a Field as the first argument:

import mongoengine as mdb
class Stuff(mdb.Document):
    things = mdb.ListField([mdb.IntField(),mdb.StringField(),mdb.ListField()])

s = Stuff(things=['1',2,[4,5]])
s.save()

I can see the final example being a useful so you might want to file an issue on the project repo.

like image 172
Steve Rossiter Avatar answered Aug 30 '26 20:08

Steve Rossiter