Opened 15 years ago

Closed 15 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: dev
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

Description

"""
Allow empty non-nullable ForeignKey fields until save()

Follow-up to Ticket #12708 (http://code.djangoproject.com/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
  None
  >>> print o.char_field
  <BLANKLINE>
  >>> print o.int_field
  None
  >>> print o.decimal_field
  None
  
No problem so far. And of course, if you try to save this, you'll get an exception:

  >>> o.save()
  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):  
  ...
  DoesNotExist
  
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):
    pass

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 by Luc Saffre, 15 years ago

comment:2 by Luke Plant, 15 years ago

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