Opened 14 years ago

Closed 13 years ago

Last modified 13 years ago

#15884 closed Bug (fixed)

Model validation allows nullable primary key field.

Reported by: JustinTArthur Owned by: JustinTArthur
Component: Database layer (models, ORM) Version: 1.3
Severity: Normal Keywords:
Cc: julie@…, alexandrul Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

If I have a primary key field that is also nullable, the model validation code is currently allowing it:

class MyModel(models.Model):
    other_model = OneToOneField(OtherModel, primary_key=True, null=True)

This behavior seems like a defect given two circumstances:

  • No SQL implementation I know of allows a primary key column to be NULL in the schema.
  • Django's CASCADE deletion will None/NULL out any null=True foreign keys (see source:/trunk/django/db/models/deletion.py@15927#L19),
    • While a SQL backend might correctly map the None to a 0 instead of NULL in the UPDATE statement, after a second deletion against the same table, you would have more than one row with primary key of 0, thus violating the uniqueness constraint intrinsic to a primary key field.

Attachments (2)

ticket_15884-patch_1.diff (948 bytes ) - added by JustinTArthur 14 years ago.
Patch to add validation error when a model field is both a primary key and nullable.
15884.diff (2.7 KB ) - added by Julie Pichon 14 years ago.

Download all attachments as: .zip

Change History (9)

comment:1 by JustinTArthur, 14 years ago

Status: newassigned

The correct link for the CASCADE interest point is actually source:/django/trunk/django/db/models/deletion.py@15927#L19

by JustinTArthur, 14 years ago

Attachment: ticket_15884-patch_1.diff added

Patch to add validation error when a model field is both a primary key and nullable.

comment:2 by JustinTArthur, 14 years ago

Component: UncategorizedDatabase layer (models, ORM)
Has patch: set

comment:3 by Jacob, 14 years ago

Needs tests: set
Triage Stage: UnreviewedAccepted

by Julie Pichon, 14 years ago

Attachment: 15884.diff added

comment:4 by Julie Pichon, 14 years ago

Cc: julie@… added
Needs tests: unset
UI/UX: unset

I'm attaching a patch with a test for the new validation behaviour -- the patch also includes JustinTArthur's diff as there was a missing double-quote around the field name.

comment:5 by alexandrul, 13 years ago

Cc: alexandrul added
Triage Stage: AcceptedReady for checkin

comment:6 by Malcolm Tredinnick, 13 years ago

Resolution: fixed
Status: assignedclosed

In [16678]:

Teach "django-admin.py validate" to forbid nullable primary keys.

Fixes #15884, with thanks to JustinTArthur and Julie Pichon.

comment:7 by Aymeric Augustin, 13 years ago

The patch breaks with Oracle, see #16694.

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