trnc
trnc

Reputation: 21577

Can't append EmbeddedDocument on save()

Here are my models:

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

and here's the code, where i try to save the embed into my document:

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

as soon as i run self.subscriber.save() i get the following error:

 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)

My code is correct (as I read in the mongoengine docs), but it won't work. Any ideas?

Upvotes: 0

Views: 75

Answers (1)

sergiuz
sergiuz

Reputation: 5529

When you first save a document, the subscriber document, make history equals "=" with a list

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

Later, when you need to add more histories, you make an update operation/query, you never append to a mongo list field.

Upvotes: 1

Related Questions