Opened 9 years ago

Closed 9 years ago

#12801 closed (duplicate)

Allow empty non-nullable ForeignKey fields until save()

Reported by: Luc Saffre Owned by: nobody
Component: Database layer (models, ORM) Version: master
Severity: Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


Allow empty non-nullable ForeignKey fields until save()

Follow-up to Ticket #12708 (

When a model has non-nullable fields (that don't have `null=True`), then Django 
still accepts to instantiate objects of that model where these fields are empty.
An exception is raised only when you try to save such an (invalid) instance.

Unfortunately this is not true for ForeignKey fields. 
If you leave a non-nullable ForeignKey field empty, Django behaves strangely: 
your instance is then like a time bomb, causing an exception when you only consult that field.

We create an Order without a Journal:
  >>> o = Order()
  >>> print o.date_field
  >>> print o.char_field
  >>> print o.int_field
  >>> print o.decimal_field
No problem so far. And of course, if you try to save this, you'll get an exception:

  Traceback (most recent call last):
  IntegrityError: 20100206_order.date_field may not be NULL
But ForeignKey fields are different: you get an exception when you only look at them:

  >>> print o.fk_field
  Traceback (most recent call last):  
This behaviour is not sane.
The line `print o.fk_field` should output `None`, like it does for other field types.


from django.db import models
class Journal(models.Model):

class Order(models.Model):
    date_field = models.DateField()
    char_field = models.CharField(max_length=20)
    int_field = models.IntegerField()
    decimal_field = models.IntegerField()
    fk_field = models.ForeignKey(Journal)

Change History (2)

comment:1 Changed 9 years ago by Luc Saffre

comment:2 Changed 9 years ago by Luke Plant

Resolution: duplicate
Status: newclosed

If you disagree with the closing of #12708, opening a duplicate bug is not the right approach - you need to bring it up on the django-dev list.

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