class DocumentMeta(BaseDocumentMeta): """Document metaclass. This meta class add ``_id`` field if it is not specified in document class. Set collection name for document to snake case of the document class name if it is not specified in Meta class attribute of a the document class. Attributes: queryset: Default query set class. default_id_field: Field to use as ``_id`` field if it is not specified in document class. """ queryset = MotorQuerySet default_id_field = ObjectIdField(name='_id', required=True, default=lambda: ObjectId()) @classmethod def _get_fields(mcls, new_class): fields, synonyms = super()._get_fields(new_class) # add _id field if needed if '_id' not in fields: fields['_id'] = mcls.default_id_field setattr(new_class, '_id', mcls.default_id_field) return fields, synonyms if not fields['_id'].required: raise ValueError("'{0}._id' field should be required.".format( new_class.__name__)) return fields, synonyms @classmethod def _get_meta_options(mcls, new_class): meta_options = super()._get_meta_options(new_class) if 'collection' not in meta_options: meta_options['collection'] = snake_case(new_class.__name__) if 'queryset' not in meta_options: meta_options['queryset'] = mcls.queryset return meta_options
(FloatField, 1.3), (BoolField, True), (DateTimeField, dt), (ObjectIdField, ObjectId('58ce6d537e592254b67a503d')), (EmailField, '*****@*****.**'), (DecimalField, Decimal('0.005')), ] @pytest.mark.parametrize('field, expected', [ (StrField(required=False), None), (IntField(required=False), None), (FloatField(required=False), None), (BoolField(required=False), None), (DateTimeField(required=False), None), (ObjectIdField(required=False), None), (EmbDocField(EmbDoc, required=False), None), (ListField(EmbDocField(EmbDoc), required=False), None), (RefField(RefDoc, required=False), None), (EmailField(required=False), None), ]) def test_field_not_exist_get_value(field, expected): class Doc(Document): value = field assert Doc().value is expected @pytest.mark.parametrize('field, default', FIELD_DEFAULT) def test_field_attributes(field, default): class Doc(Document):
class Doc(Document): _id = ObjectIdField(required=True, default=lambda: ObjectId())
class Comment(EmbeddedDocument): """Comment model.""" _id = ObjectIdField(required=True, default=lambda: ObjectId()) body = StrField(required=True, allow_blank=False) author = RefField(User, required=True, mongo_name='user')