﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
21194	Foreign Keying To A Field With An Empty String Value Converts To Null Database Value	albertyw@…	nobody	"If I have these two models:

{{{
class A(models.Model):
    b = models.ForeignKey(B)

class B(models.Model):
    asdf = models.CharField(max_length = 10, primary_key=True)
}}}

then

{{{
empty = B()
empty.asdf = ''
empty.save()
alpha = A()
alpha.b = empty
alpha.save()
}}}

will break because django will try to convert the asdf_id field to NULL when creating the sql statement.  (I'm running MySQL, but I'm guessing this affects non-mysql databases)

The traceback is 
{{{
  File ""/usr/local/lib/python2.7/dist-packages/django/db/models/base.py"", line 546, in save
    force_update=force_update, update_fields=update_fields)
  File ""/usr/local/lib/python2.7/dist-packages/django/db/models/base.py"", line 626, in save_base
    rows = manager.using(using).filter(pk=pk_val)._update(values)
  File ""/usr/local/lib/python2.7/dist-packages/django/db/models/query.py"", line 605, in _update
    return query.get_compiler(self.db).execute_sql(None)
  File ""/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py"", line 1018, in execute_sql
    cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
  File ""/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py"", line 840, in execute_sql
    cursor.execute(sql, params)
  File ""/usr/local/lib/python2.7/dist-packages/django/db/backends/util.py"", line 41, in execute
    return self.cursor.execute(sql, params)
  File ""/usr/local/lib/python2.7/dist-packages/django/db/backends/mysql/base.py"", line 120, in execute
    return self.cursor.execute(query, args)
  File ""/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py"", line 176, in execute
    if not self._defer_warnings: self._warning_check()
  File ""/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py"", line 92, in _warning_check
    warn(w[-1], self.Warning, 3)
_mysql_exceptions.Warning: Column 'base_element_id' cannot be null
}}}

I've specifically found that the get_db_prep_save function in db/models/fields/related.py:1042 is changing the empty string value over to None, which then gets converted to NULL in sql.  I also noticed there's an unused ""empty_strings_allowed = False"" in that function's class.  "	Bug	closed	Database layer (models, ORM)	dev	Normal	duplicate		bmispelon@…	Accepted	1	0	1	1	0	0
