Empty BinaryField != b'' on Python 2
|Reported by:||Owned by:||Grzegorz Ślusarek|
|Component:||Database layer (models, ORM)||Version:||master|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
Description (last modified by )
In Python 2, at least under SQLite, the initial value for an empty binary field behaves inconsistently. The ORM thinks it's an empty
b''. The database connection manager thinks it's a buffer. Now, the buffer evaluates to
False and has zero length. So it'll mostly work. But not always -- and most importantly to me, not in my unit tests!
Note this was not a problem under Python 3.4.
Steps to Reproduce
Using Python 2.7.8, SQLite, and either Django 1.7rc2 or Django @ edcc75e5ac5b9dc2f174580e7adacd3be586f8bd (HEAD at the time of this writing; the error exists in both places)
- Make a new project and a new app and add the app to settings.py
- Fill in
from django.db import models class BinModel(models.Model): data = models.BinaryField()
- Run from the command line:
(venv) $ ./manage.py makemigrations app && ./manage.py migrate && ./manage.py shell
- Run from the resulting Python shell
>>> from app import models; m = models.BinModel(); m.save(); n = models.BinModel.objects.get() >>> m.data '' >>> m.data == b'' True >>> n.data <read-write buffer ptr 0x10eaa62b0, size 0 at 0x10eaa6270> >>> n.data == b'' False >>> bool(n.data) False >>> len(n.data) 0 >>> bytes(n.data) ''
Note that the same problem persisted when I had a default value for the field. There was no problem under Python 3.4.
Change History (9)
comment:1 Changed 2 years ago by
|Severity:||Release blocker → Normal|
|Version:||1.7-rc-2 → master|
comment:3 Changed 2 years ago by
|Summary:||Empty BinaryField != b'' in Python 2/SQLite → Empty BinaryField != b'' on Python 2|
comment:6 Changed 23 months ago by
|Owner:||changed from nobody to Grzegorz Ślusarek|
|Status:||new → assigned|