hmarr/mongoengine — Issue #436: meta["id_field"] and ReferenceField
Author: anti-social
Created: 2012-02-23 15:39:43+00:00
State: open

I have next model:

```python
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:

```python
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:

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