2

Is it possible to create a custom ObjectId in a django model that is being saved to a mongodb using mongodb-engine? I've tried to do this passing the string I want into the ObjectId type, Flight(_id=ObjectId(myid)) for example but then this gives me an error saying that the string is not a valid id. Is it possible to override the id with a custom one? And is there somewhere where I can read about this or what the rules for creating an ID are?

example:

File "/usr/local/lib/python2.7/dist-packages/bson/objectid.py", line 172, in __validate raise InvalidId("%s is not a valid ObjectId" % oid) InvalidId: short_profile_4fcad5e8e5095f5a4f000000 is not a valid ObjectId

1
  • What is the exact error, please? Commented Feb 17, 2011 at 12:12

1 Answer 1

0

For sure you can your custom objectId, check objectId documentation for that , but i don't unsdestand fot what you need it.

Instead of ObjectId you can use any type that you want. So you can make _id string and insert any strting value instead of mongo ObjectId. But your custom _id must be unique for each member of a collection. This is enforced if the collection has an index on _id, which is the case by default.

from documentation

Although _id values can be of any type, a special BSON datatype is provided for object ids. This type is a 12-byte binary value designed to have a reasonably high probability of being unique when allocated. All of the officially-supported MongoDB drivers use this type by default for _id values. Also, the Mongo database itself uses this type when assigning _id values on inserts where no _id value is present.

Sign up to request clarification or add additional context in comments.

1 Comment

So what I actually want is to set a string as my _id but I keep getting this error: AutoField (default primary key) values must be strings representing an ObjectId on MongoDB (got u'ryanair-DU...' instead) Any ideas what might be wrong? My model has _id = models.CharField(db_index=True)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.