1

I'm working on a very simple application as a use case for integrating MongoDB with web2py. In one section of the application, I'm interested in returning a list of products:

My database table:

db.define_table('products',
Field('brand', label='Brand'),
Field('photo', label='Photo'),
...
Field('options', label='Options'))

My controller:

def products():
qset = db(db['products'])
grid = qset.select()
return dict(grid=grid) 

My view:

{{extend 'layout.html'}}
<h2>Product List</h2>
{{=grid}}

The products are returned without issue. However, the products._id field returns values in the form '26086541625969213357181461154'. If I switch to the shell (or python) and attempt to query my database based on those _ids, I can't find any of the products.

As you would expect, the _ids in the database are ObjectIds that look like this '544a481b2ceb7c3093a173a2'. I'd like to my view to return the ObjectIds and not the long strings. Simple, but I'm having trouble with it.

2 Answers 2

1

When constructing the DAL Row object for a given MongoDB record, the ObjectId is represented by converting to a long integer via long(str(value), 16). To convert back to an ObjectId, you can use the object_id method of the MongoDB adapter:

object_id = db._adapter.object_id('26086541625969213357181461154')

Of course, if you use the DAL to query MongoDB, you don't have to worry about this, as it handles the conversion automatically.

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

Comments

1

Although it makes perfect sense, I wasn't able to make Anthony's answer work. So, I just hacked it:

hex(value).replace("0x","").replace("L","")

1 Comment

Hmm, not sure why db._adapter.object_id doesn't work for you, but in any case, it just ends up doing hex(arg)[2:].rstrip('L').zfill(24), so mostly the same as your code.

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.