Permalink
Browse files

Added handling for callable collections

1 parent 607711c commit c62b6321adaba6c3eb54ce2dc2c1bd3069568399 @rozza rozza committed May 24, 2011
Showing with 22 additions and 0 deletions.
  1. +5 −0 mongoengine/base.py
  2. +17 −0 tests/document.py
View
@@ -297,6 +297,11 @@ def __new__(cls, name, bases, attrs):
# DocumentMetaclass before instantiating CollectionManager object
new_class = super_new(cls, name, bases, attrs)
+ # Allow dynamically-generated collection names. Pass the newly
+ # created class so the callee has access to __module__, etc.
+ if callable(meta['collection']):
+ new_class._meta['collection'] = meta['collection'](new_class)
@ra21vi

ra21vi Jul 17, 2012

Dynamic collection name does not work. Since it is in new, it calls the callable just for once (for first time only) when defining the class/object. After that, the same name is used.
Please fix it.

@rozza

rozza Jul 18, 2012

@ra21vi its not broken - thats the intent. A Class can only ever have a single collection.

If you need different please add a ticket.

+
# Provide a default queryset unless one has been manually provided
if not hasattr(new_class, 'objects'):
new_class.objects = QuerySetManager()
View
@@ -61,6 +61,23 @@ class Person(Document):
# Ensure Document isn't treated like an actual document
self.assertFalse(hasattr(Document, '_fields'))
+ def test_dynamic_collection_naming(self):
+
+ def create_collection_name(cls):
+ return "PERSON"
+
+ class DynamicPerson(Document):
+ name = StringField()
+ age = IntField()
+
+ meta = {'collection': create_collection_name}
+
+ collection = DynamicPerson._get_collection_name()
+ self.assertEquals(collection, 'PERSON')
+
+ DynamicPerson(name='Test User', age=30).save()
+ self.assertTrue(collection in self.db.collection_names())
+
def test_get_superclasses(self):
"""Ensure that the correct list of superclasses is assembled.
"""

3 comments on commit c62b632

in the documentation it shows using the above code in a Mixin... but unfortunately it doesn't seem to work

http://mongoengine.org/docs/v0.5/upgrade.html#default-collection-naming

Thanks for pointing that out - had a name collision in the test suite that should have caught this. I've fixed in the master branch

Thanks for pointing that out - had a name collision in the test suite that should have caught this. I've fixed in the master branch

Please sign in to comment.