meta["id_field"] and ReferenceField #436

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

Comments

Projects
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')
g1.save()
g2 = ImportProductGroup(name='Test 2', parent_group=g1)
g2.save()
----> 1 p.save()

/home/alexk/v/uaprom-arch/lib/python2.7/site-packages/mongoengine/document.pyc in save(self, safe, force_insert, validate, write_options, _refs)
    142 
    143         if validate:
--> 144             self.validate()
    145 
    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.')
    154 
--> 155         self.validate(value)
    156 
    157 

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

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

I think we should use pk attribute instead id:

fields.py:

631    id_ = document.pk

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

rozza commented Feb 23, 2012

I agree with this, however document.id 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