简体   繁体   English

Python MongoEngine中的异构列表

[英]Heterogeneous Lists in Python MongoEngine

does MongoEngine supports having different data types in a list? MongoEngine支持在列表中使用不同的数据类型吗? For example, I'd like a ListField() to store IntField() as well as StringField() . 例如,我想要一个ListField()来存储IntField()以及StringField() Is there a way to do this in MongoEngine? 在MongoEngine中有没有办法做到这一点?

The ListField does not enforce a datatype unless you ask it to. 除非您要求,否则ListField不会强制实施数据类型。 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: 这会抛出TypeError因为它强制执行数据类型:

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: 这会抛出AttributeError因为它期望Field作为第一个参数:

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. 我可以看到最后的示例是有用的,因此您可能希望在项目仓库中提交问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM