gpt4 book ai didi

mongodb - 为什么我不能直接分配 ListField 的值?

转载 作者:可可西里 更新时间:2023-11-01 10:02:07 24 4
gpt4 key购买 nike

我在使用 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']

这是预期的行为吗?或者我错过了什么?

最佳答案

问题是我忘记了 StringField 之后的括号......哎哟。

class Chart(Document):
...
x = ListField(StringField())
y = ListField(StringField())

关于mongodb - 为什么我不能直接分配 ListField 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49614435/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com