meta["id_field"] and ReferenceField #436

anti-social opened this Issue Feb 23, 2012 · 1 comment


None yet
2 participants

I have next model:

class ImportProductGroup(Document):
    _id = ObjectIdField()
    id = IntField()
    name = StringField(max_length=100, required=True)
    parent_group = ReferenceField('ImportProductGroup')

    meta = {
        'collection': 'import_product_group',
        'id_field': '_id',

And when I trying to save document with reference I've got an error:

g1 = ImportProductGroup(name='Test 1')
g2 = ImportProductGroup(name='Test 2', parent_group=g1)
----> 1

/home/alexk/v/uaprom-arch/lib/python2.7/site-packages/mongoengine/document.pyc in save(self, safe, force_insert, validate, write_options, _refs)
    143         if validate:
--> 144             self.validate()
    146         if not write_options:

/home/alexk/v/uaprom-arch/lib/python2.7/site-packages/mongoengine/base.pyc in validate(self)
    622             if value is not None:
    623                 try:
--> 624                     field._validate(value)
    625                 except (ValueError, AttributeError, AssertionError), e:
    626                     raise ValidationError('Invalid value for field named "%s" of type "%s": %s'

/home/alexk/v/uaprom-arch/lib/python2.7/site-packages/mongoengine/base.pyc in _validate(self, value)
    153                 raise ValueError('validation argument must be a callable.')
--> 155         self.validate(value)

/home/alexk/v/uaprom-arch/lib/python2.7/site-packages/mongoengine/fields.pyc in validate(self, value)
    648         if isinstance(value, Document) and is None:
--> 649             raise ValidationError('You can only reference documents once '
    650                                   'they have been saved to the database')

ValidationError: You can only reference documents once they have been saved to the database

I think we should use pk attribute instead id:

631    id_ =

648    if isinstance(value, Document) and is None:

rozza commented Feb 23, 2012

I agree with this, however is used internally also so this fix would be bigger and have knock on impacts.

For now please refrain from mixing id and another _id key.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment