Skip to content

Duplicate keyword '_binary' failure when using BinaryField in Django #549

@ace-han

Description

@ace-han

Process to reproduce

# models.py
from django.db import models
from django.utils.translation import ugettext_lazy as _

class DbBasedFile(models.Model):
  filename = models.CharField(_('filename'), max_length=128)
  content = models.BinaryField(_('content'))
  size = models.PositiveIntegerField(_('size'))

  class Meta:
      unique_together = (('filename', ), )
  
  def __str__(self):
      return '{}, filename: {}'.format(self.__class__.__name__, self.filename)

if __name__ == '__main__':
  DbBasedFile(filename='1.txt', content=b'abc', size=3).save()

will get error

ProgrammingError at /api/misc/dbfiles/file/
(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '_binary'abc', 3)'

The pre-generated sql is like below

str: INSERT INTO `misc_dbbasedfile` (`filename`, `content`, `size`) VALUES (%s, _binary %s, %s)

The final sql is like below

bytes: b"INSERT INTO `misc_dbbasedfile` (`filename`, `content`, `size`) VALUES ('1.txt', _binary _binary'abc', 3)"

As we can see, there are two _binary in the final sql which will fail eventually
After a little debugging, I found these _binary in

django/django/db/backends/mysql/operations.py.DatabaseOperations.binary_placeholder_sql
django/db/models/fields/__init__.py.BinaryField.get_placeholder
pymysql/converters.py.escape_bytes

, which I think is the root cause

I think we can refer to below links to get a solution,
PyMySQL/mysqlclient#106
PyMySQL/mysqlclient#140

Maybe making it optional to add _binary prefix is a nice idea 😄

PyMySQL is great in its pure python implementation to ease the installation on diff OS platform.
I really want this to be fixed, please kindly help, thx.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions