Opened 15 years ago

Closed 8 years ago

#11866 closed Bug (duplicate)

non-null FK to a CharField primary key fails when key value is the empty string, giving "[model.fk_col] may not be NULL"

Reported by: Andrew Badr Owned by: nobody
Component: Database layer (models, ORM) Version: 1.1
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Model A has a CharField primary_key. Model B has a ForeignKey field to model A. If an instance of A has a row with an empty-string in the primary key column, no B instance can point to it. Attempting to create such a B instance fails with "[model.fk_col] may not be NULL". Repro'd with PG and sqlite3.

Change History (9)

comment:1 by Andrew Badr, 15 years ago

Seems to be caused by ForeignKey.get_db_prep_save (called from Model.save_base):

    def get_db_prep_save(self, value):
        if value == '' or value == None:
            return None
        ...

Unsure where to go since I don't know the reasoning behind this code. Is this due to forms assigning the empty-string to fields left blank?

comment:2 by Andrew Badr, 14 years ago

Owner: changed from Andrew Badr to nobody

comment:3 by Jacob, 14 years ago

Triage Stage: UnreviewedDesign decision needed

in reply to:  description comment:4 by syko, 14 years ago

Replying to andrewbadr:

Model A has a CharField primary_key. Model B has a ForeignKey field to model A. If an instance of A has a row with an empty-string in the primary key column, no B instance can point to it. Attempting to create such a B instance fails with "[model.fk_col] may not be NULL". Repro'd with PG and sqlite3.

I encountered a similar problem in django 1.2.1 using MySQL, but I don't think it has anything to do with foreign keys. The documentation says "Note that empty string values will always get stored as empty strings, not as NULL", which is clearly not the case. Assigning a empty ("") string value to a CharField(null=False, blank=True) and saving the model will throw a "column cannot be NULL" error.
Thus the only way to store empty values in CharFields is having null=True.

comment:5 by Julien Phalip, 13 years ago

Severity: Normal
Type: Bug

comment:6 by Aymeric Augustin, 12 years ago

UI/UX: unset

Change UI/UX from NULL to False.

comment:7 by Aymeric Augustin, 12 years ago

Easy pickings: unset

Change Easy pickings from NULL to False.

comment:8 by Anssi Kääriäinen, 11 years ago

Triage Stage: Design decision neededAccepted

This should be fixed at some point. The fix should involve making sure '' works as expected in other parts of Django, too.

Last edited 11 years ago by Anssi Kääriäinen (previous) (diff)

comment:9 by Tim Graham, 8 years ago

Resolution: duplicate
Status: newclosed

Duplicate of #19299; fixed in Django 1.7.

Note: See TracTickets for help on using tickets.
Back to Top