diff --git a/docs/changelog.rst b/docs/changelog.rst index f0adcbe5..58859a58 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -5,6 +5,7 @@ Changelog Changes in 0.6.X ================ +- Fixed BinaryField python value issue (MongoEngine/mongoengine#48) - Fixed queryset manager issue (MongoEngine/mongoengine#52) - Fixed FileField comparision (hmarr/mongoengine#547) diff --git a/mongoengine/fields.py b/mongoengine/fields.py index 89b81cdb..27434e67 100644 --- a/mongoengine/fields.py +++ b/mongoengine/fields.py @@ -845,12 +845,9 @@ class BinaryField(BaseField): def to_mongo(self, value): return Binary(value) - def to_python(self, value): - return "%s" % value - def validate(self, value): - if not isinstance(value, basestring): - self.error('BinaryField only accepts string values') + if not isinstance(value, (basestring, Binary)): + self.error('BinaryField only accepts string or bson Binary values') if self.max_bytes is not None and len(value) > self.max_bytes: self.error('Binary value is too long') diff --git a/tests/test_fields.py b/tests/test_fields.py index 4e708563..29f5fe97 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -6,6 +6,7 @@ import StringIO import tempfile import gridfs +from bson import Binary from decimal import Decimal from mongoengine import * @@ -1428,7 +1429,7 @@ class FieldTest(unittest.TestCase): attachment_1 = Attachment.objects().first() self.assertEqual(MIME_TYPE, attachment_1.content_type) - self.assertEqual(BLOB, attachment_1.blob) + self.assertEqual(BLOB, str(attachment_1.blob)) Attachment.drop_collection() @@ -1455,7 +1456,7 @@ class FieldTest(unittest.TestCase): attachment_required = AttachmentRequired() self.assertRaises(ValidationError, attachment_required.validate) - attachment_required.blob = '\xe6\x00\xc4\xff\x07' + attachment_required.blob = Binary('\xe6\x00\xc4\xff\x07') attachment_required.validate() attachment_size_limit = AttachmentSizeLimit(blob='\xe6\x00\xc4\xff\x07') @@ -1467,6 +1468,18 @@ class FieldTest(unittest.TestCase): AttachmentRequired.drop_collection() AttachmentSizeLimit.drop_collection() + def test_binary_field_primary(self): + + class Attachment(Document): + id = BinaryField(primary_key=True) + + Attachment.drop_collection() + + att = Attachment(id=uuid.uuid4().bytes).save() + att.delete() + + self.assertEqual(0, Attachment.objects.count()) + def test_choices_validation(self): """Ensure that value is in a container of allowed values. """