namlook / mongokit

MongoKit framework try to keep its simplicity when you manage mongodb in python. MongoKit was developed to be fast and light with KISS and DRY in mind. MongoKit brings structured schema and validation layer on top of the great pymongo driver. Discuss with us on Google group : http://groups.google.com/group/mongokit or follow the news on Twitter: http://twitter.com/namlook
http://namlook.github.com/mongokit/
Other
677 stars 132 forks source link

get missing values from defaults #71

Open matejcik opened 12 years ago

matejcik commented 12 years ago

it would be nice to have something like this:

class User(Document):
    __collection__ = 'users'
    structure = {
        'name': unicode,
        'password': unicode,
        'description': unicode,
    }
    default_values = { 'description': u'i have not filled in a description' }
    use_transparent_defaults = True

u1 = fetch_user_with_description()
print u1.description # prints value from db
u2 = fetch_user_without_description()
print u2.description # takes value from default_values

this looks like a nice alternative to migration suppport for schemaless documents

namlook commented 12 years ago

This is the attended behavior. u2.description should return the filled value. What's wrong ?

matejcik commented 12 years ago

well, it doesn't. (in MongoKit 0.7.2 at least)

with the proposed enhancement, the following code would work:

from mongokit import Document
from mongokit import Connection as KitCon
from pymongo import Connection as MoCon

mc = MoCon()
kc = KitCon()

# create an "unexpected" record directly through PyMongo
mc.example.drop_collection('users')
mtable = mc.example.users
mtable.insert({'name':'hello','password':'world'})

@kc.register
class User(Document):
    __collection__ = 'users'
    structure = {
        'name': unicode,
        'password': unicode,
        'description': unicode,
    }
    default_values = { 'description': u'hello world' }

user = kc.example.User.find_one()
assert user['description'] == u'hello world'