无法在save()上附加EmbeddedDocument

时间:2016-07-31 20:05:43

标签: python mongodb flask mongoengine

以下是我的模特:

class Subscriber(Document):
  service = StringField()
  history = EmbeddedDocumentListField('SubscriberHistory')

  def __str__(self):
      return self.service

class SubscriberHistory(EmbeddedDocument):
  action = StringField()
  content = DictField()
  created_at = DateTimeField(required=True, default=datetime.utcnow)

  def __str__(self):
    return self.action

这里是代码,我尝试将嵌入保存到我的文档中:

subscriber_history = SubscriberHistory()
subscriber_history.action = 'inbound',
subscriber_history.content = event
self.subscriber.history.append(subscriber_history)
self.subscriber.save()

我一跑self.subscriber.save()我就会收到以下错误:

 File "/foo/bar/env/lib/python3.5/site-packages/mongoengine/base/fields.py", line 415, in validate
 self.error('Invalid %s item (%s)' % (field_class, value),
 TypeError: __repr__ returned non-string (type tuple)

我的代码是正确的(正如我在mongoengine文档中所读到的那样),但它不会起作用。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

首次保存文档时,订阅者文档的历史记录等于“=”并带有列表

subscriber.history = [subscriber_history]
subscriber.save()

稍后,当您需要添加更多历史记录时,进行更新操作/查询,您永远不会附加到mongo列表字段。