我在使用mongoengine(python3)创建新文档时遇到了麻烦。似乎无法直接向ListFields添加列表。
我有以下设置:
# CONNECTION AND SETUP:
from mongoengine import *
connect('mongoengine_testing', host='localhost', port=27017)
class Chart(Document):
instrument_ticker = StringField(max_length=40)
chart_type = StringField(max_length=120)
chart_name = StringField(max_length=120)
x = ListField(StringField)
y = ListField(StringField)
当我尝试添加这样的新图表文档时,它失败了:
## THIS DOESN'T WORK:
chart = Chart(
instrument_ticker = 'EURUSD',
chart_type = 'weekday_avg',
chart_name = 'Average Weekday',
x = ['1', '2', '3', '4', '5'],
y = ['13', '12', '24', '55', '32']
)
### ERROR MESSAGE
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-22-17d67eea1df7> in <module>()
4 chart_name = 'Average Weekday',
5 x = ['1', '2', '3', '4', '5'],
----> 6 y = ['13', '12', '24', '55', '32']
7 )
~/Development/python/mongoengine/mongo_env/lib/python3.4/site-packages/mongoengine/base/document.py in __init__(self, *args, **values)
113 field = self._fields.get(key)
114 if field and not isinstance(field, FileField):
--> 115 value = field.to_python(value)
116 setattr(self, key, value)
117 else:
~/Development/python/mongoengine/mongo_env/lib/python3.4/site-packages/mongoengine/base/fields.py in to_python(self, value)
324 self.field._auto_dereference = self._auto_dereference
325 value_dict = {key: self.field.to_python(item)
--> 326 for key, item in list(value.items())}
327 else:
328 Document = _import_class('Document')
~/Development/python/mongoengine/mongo_env/lib/python3.4/site-packages/mongoengine/base/fields.py in <dictcomp>(.0)
324 self.field._auto_dereference = self._auto_dereference
325 value_dict = {key: self.field.to_python(item)
--> 326 for key, item in list(value.items())}
327 else:
328 Document = _import_class('Document')
TypeError: to_python() missing 1 required positional argument: 'value'
但是,当我按照这样的多个步骤创建它时,它可以工作:
## THIS WORKS:
chart = Chart(
instrument_ticker = 'EURUSD',
chart_type = 'weekday_avg',
chart_name = 'Average Weekday',
)
chart.x = ['1', '2', '3', '4', '5']
chart.y = ['13', '12', '24', '55', '32']
这是预期的行为吗?或者我错过了什么?
答案 0 :(得分:2)
问题是我在StringField之后忘记了括号。哎哟。
class Chart(Document):
...
x = ListField(StringField())
y = ListField(StringField())