Question

How can I add several entries to a document at once in Flask using MongoEngine/Flask-MongoEngine?

I tried to iterate over the dictionary that contains my entries. I simplified the example a bit, but originally the data is a RSS file that my Wordpress spits out and that I parsed via feedparser.

But the problem obviously is that I cannot dynamically generate variables that hold my entries before being saved to the database.

Here is what I tried so far.

How can I add the entries to my MongoDB database in bulk?

# model
class Entry(db.Document):
    created_at = db.DateTimeField(
        default=datetime.datetime.now, required=True),
    title = db.StringField(max_length=255, required=True)
    link = db.StringField(required=True)

# dictionary with entries
e = {'entries': [{'title': u'title1',
                  'link': u'http://www.me.com'
                  },
    {'title': u'title2',
     'link': u'http://www.me.com/link/'
     }
]
}

# multiple entries via views
i = 0
while i<len(e['entries']):
      post[i] = Entry(title=e['entries'][i]['title'], link=e['entries'][i]['title'])
      post[i].save();
      i += 1

Edit 1:

I thought about skipping the variables alltogether and translate the dictionary to the form that mongoengine can understand.

Because when I create a list manually, I can enter them in bulk into MongoDB:

newList = [RSSPost(title="test1", link="http://www.google.de"),
            RSSPost(title="test2", link="http://www.test2.com")]

RSSPost.objects.insert(newList)

This works, but I could not translate it completely to my problem.

I tried

f = []

for x in e['entries']:
    f.append("insert " + x['link'] + " and " + x['title'])

But as you see I could not recreate the list I need.

How to do it correctly?

Was it helpful?

Solution

# dictionary with entries
e = {'entries': [{'title': u'title1',
                  'link': u'http://www.me.com'
                  },
    {'title': u'title2',
     'link': u'http://www.me.com/link/'
     }
]
}

How is your data/case different from the examples you posted? As long as I'm not missing something you should be able to instantiate Entry objects like:

entries = []
for entry in e['entries']:
    new_entry = Entry(title=entry['title'], link=entry['link'])
    entries.append(new_entry)

Entry.objects.insert(entries)

OTHER TIPS

Quick and easy way:

for i in e['entries']:
    new_e = Entry(**i)
    new_e.save()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top