Felipe
Felipe

Reputation: 440

Use a custom ID type in mongodb usyng python

Im using mongodb to as a storage backend for some of my information in a Django 1.5 app.

Every document stored in the mongodb collection has an _id field which is a dict composed of several strings. Now when I try to retrieve this information I map the document to a model class using mongoengine:

from mongoengine import *

class MyClass(Document):
    _id = DictField()

At the view I do:

documents = MyClass.objects
print documents

When I call the view I get a TypeError

TypeError at /viewname/
id must be an instance of (str, unicode, ObjectId), not <type 'dict'>

Even worse is that when I use the save rutine

obj = MyClass({"tag":"sometag"})
obj.save()

I get the exat same error, but at the db collection the document with _id={"tag":"sometag"} was created.

Any ideas of what could be happening? It could be the same that is happening here

Note: I tried ussing the EmbeddedDocumentField but the results are the same (the error takes my Embedded class name instead of 'dict')

Upvotes: 3

Views: 3398

Answers (2)

Felipe
Felipe

Reputation: 440

I found it:

I was missing the primary_key argument. If I change it at the model:

class MyClass(Document):
    id = DictField(primary_key=True)

It starts working at both operations, read and write.

Here is the official doc: Mongoengine

Upvotes: 6

DhruvPathak
DhruvPathak

Reputation: 43245

Do not use dict for _id field, use a hash of that dictionary.

Eg. sha1 of the json representation of the dictionary , or just hash if number of records are not that much.

Upvotes: 1

Related Questions